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,599
  • 3
  • 10
  • 16

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
  • 351,820
  • 24
  • 303
  • 358
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,700
  • 21
  • 28
1

try

 temp.sort(function(a, b) {return a.rank - b.rank});
user7417866
  • 1,146
  • 1
  • 7
  • 12