Vicheanak
Vicheanak

Reputation: 6694

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

Upvotes: 2

Views: 196

Answers (3)

Joe
Joe

Reputation: 82634

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

Upvotes: 4

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707876

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

Upvotes: 3

Related Questions