5

I have an array like this

var temp = [{"rank":3,"name":"Xan"},{"rank":1,"name":"Man"},{"rank":2,"name":"Han"}]

I am trying to sort it as follows

 temp.sort(function(a){ a.rank})

But its n ot working.Can anyone suggest help.Thanks.

Daniel
  • 1,939
  • 3
  • 11
  • 18

3 Answers3

6

With Array#sort, you need to check the second item as well, for a symetrical value and return a value.

var temp = [{ rank: 3, name: "Xan" }, { rank: 1, name: "Man" }, { rank: 2, name: "Han" }];

temp.sort(function(a, b) {
    return a.rank - b.rank;
});

console.log(temp);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You must compare them inside the sort function. If the function returns a negative value, a goes before b (in ascending order), if it's positive, b goes before a. If the return value is 0, they are equal:

temp.sort(function(a, b) {
    if (a.rank < b.rank) {
        return -1;
    } else if (a.rank > b.rank) {
        return 1;
    } else {
        return 0;
    }
});

You can use a shortcut method that subtracts the numbers to get the same result:

temp.sort((a, b) {
    return a.rank - b.rank;
});

For descending order:

temp.sort((a, b) {
    return b.rank - a.rank;
});

ES6 shortcut:

temp.sort((a, b) => b.rank - a.rank;
Gorka Hernandez
  • 3,890
  • 23
  • 29
1

try

 temp.sort(function(a, b) {return a.rank - b.rank});
Abhinav
  • 1,202
  • 1
  • 8
  • 12