0

There is a simple part of the code where I need to sort an array of objects by the next way (sorting array objects by a prop first and then by the b prop). So the result should look's like:

var a = [
    {
        a: 1,
        b: 2
    },
    {
        a: 1,
        b: 4
    },
    {
        a: 1,
        b: 5
    },
    {
        a: 2,
        b: 1
    },
    {
        a: 2,
        b: 3
    },
    {
        a: 2,
        b: 4
    }
]

But unfortunately, my code below doesn't seem to work well. Could someone help me? Thank you in advance.

var a = [
    {
        a: 2,
        b: 4
    },
    {
        a: 2,
        b: 3
    },
    {
        a: 1,
        b: 2
    },
    {
        a: 1,
        b: 4
    },
    {
        a: 1,
        b: 5
    },
    {
        a: 2,
        b: 1
    }
]

a.sort((first, second) => first.a - second.a && first.b - second.b ? 1 : -1)

console.log(a)

2
  • 1
    a.sort((first, second) => first.a - second.a || first.b - second.b) Commented Feb 14, 2019 at 17:48
  • @NinaScholz thank you! :) Commented Feb 14, 2019 at 17:49

1 Answer 1

0

You need to check the first property a if they are equal then go for b.

const a = [{"a":2,"b":4},{"a":2,"b":3},{"a":1,"b":2},{"a":1,"b":4},{"a":1,"b":5},{"a":2,"b":1}];

a.sort((obj1 ,obj2) => obj1.a - obj2.a ? obj1.a - obj2.a : obj1.b -obj2.b );
console.log(a);

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

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.