How to sort a collection of objects in an Array in Javascript?
I have a collection objects in an array,
[{A:2, B:2},{A:2, B:3},{A:1, B: 2}, {A:1, B:1}]
I would like to have a sort result of property A then property B. Therefore, as a result it should be:
[{A:1, B:1}, {A:1, B:2}, {A:2, B:2}, {A:2, B:3}]
开发者_如何转开发
Sort by A then by B. This sort works, because if A == A
then A - A
is 0
. And 0 || anything
is always anything
. So it compares A
then differs to B
is A's are equal.
var list = [{A:2, B:2},{A:2, B:3},{A:1, B: 2}, {A:1, B:1}];
list.sort(function (a, b) {
return a.A - b.A || a.B - b.B
})
Using fully cross browser sort and the benefits of lazy evaluation
You use a custom sort callback that first compares the A values and then, if those are equal uses the B values, thus creating primary and secondary keys for the sort:
var collection = [{A:2, B:2},{A:2, B:3},{A:1, B: 2}, {A:1, B:1}];
collection.sort(function(a, b){
if (a.A != b.A) {
return(a.A - b.a);
} else {
return(a.B - b.B);
}
});
try following code
[{A:2, B:2},{A:2, B:3},{A:1, B: 2}, {A:1, B:1}]
.sort(function(a, b) { return (a.A< b.A) ? -1 : (a.A> b.A) ? 1 : 0 })
.sort(function(a, b) { return (a.B< b.B) ? -1 : (a.B> b.B) ? 1 : 0 });
精彩评论