Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Array sort with primary and secondary value

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!