1

Is there a way to sort an array of objects using a primary and secondary value? What i mean is an array like this:

[
    { primary: 0, secondary: 'a' },
    { primary: 1, secondary: 'a' },
    { primary: 1, secondary: 'b' },
    { primary: 0, secondary: 'b' }
]

will be sorted using the primary value, so the first two objects with the primary value of 0 come first then the values of 1 come second, and then it will be again sorted by the secondary value and it will result in the array becoming

[
    { primary: 0, secondary: 'a' },
    { primary: 0, secondary: 'b' },
    { primary: 1, secondary: 'a' },
    { primary: 1, secondary: 'b' }
]

im havent really touched the Array.sort() before so im trying to find out how to do this, any help will be appreciated!

KyleRifqi
  • 489
  • 2
  • 15

1 Answers1

0

You can use Array#sort.

Comparison would be by primary first (numeric), or by secondary if equal (string using String#localeCompare)

const arr = [ { primary: 0, secondary: 'a' }, { primary: 1, secondary: 'a' }, { primary: 1, secondary: 'b' }, { primary: 0, secondary: 'b' } ];

const res = arr.sort((a, b) => 
  a.primary - b.primary || a.secondary.localeCompare(b.secondary)
);

console.log(res);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48