How to sort in js?

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 not working. Can someone offer help. Thank.

+4
source share
3 answers

With Array#sortyou, you also need to check the second element for a character value and return the 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; }
Run codeHide result
+6
source

You must compare them inside the sort function . If the function returns a negative value, a goes to b (in ascending order), if it is positive, b goes to 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;
    }
});

, , :

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

:

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

ES6:

temp.sort((a, b) => b.rank - a.rank;
+2

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

Source: https://habr.com/ru/post/1671804/


All Articles