How to perform sort in js?

故事扮演 提交于 2020-07-08 10:32:20

问题


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.


回答1:


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; }



回答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;



回答3:


try

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


来源:https://stackoverflow.com/questions/42671437/how-to-perform-sort-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!