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)
Max Travis
  • 1,228
  • 4
  • 18
  • 41

1 Answers1

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);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44