I have an array of objects, for example:
var a = [
{ value: 500, name: 'ccc' },
{ value: 100, name: 'bbb' },
{ value: 500, name: 'aaa' },
{ value: 300, name: 'eee' },
];
And I need to sort it by descending order of value field, AND if value field are equals -- then sort this two objects by alphabet order of field name .
I try something like this:
a.sort(function (a, b) {
return b["value"] - a["value"] || (a["name"] > b["name"]) ? 1: -1;
});
But this does not result in
500,aaa
500,ccc
300,eee
100,bbb
as I would expect
The problem is operator precedence, you need to parenthesize properly.
a.sort(function (a, b) {
return (b["value"] - a["value"]) || ((a["name"] > b["name"]) ? 1: -1);
});
The logical operators have higher precedence than the ternary operator, so you need wrap the ternary expression in parentheses. I've added additional redundant parentheses to make everything explicit.
Tested result:
[{"value":500,"name":"aaa"},
{"value":500,"name":"ccc"},
{"value":300,"name":"eee"},
{"value":100,"name":"bbb"}]
Try to create a separate function.
function compare(a,b) {
if (a.value< b.value)
return -1;
if (a.value> b.value)
return 1;
if(a.value == b.value)
if (a.name< b.name)
return -1;
if (a.name> b.name)
return 1;
return 0;
}
a.sort(compare);
Here is working example : http://jsfiddle.net/8ZUdF/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.