2

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Nice edit of your original post which didn't accomplish the desired result (which is why I wrote my answer).
3

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.