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

67
Views
Sorting nested array not returning sorted results

I have the following code, which seems to be doing the correct thing, but when I log the array object it never changes:

let data = [
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'CA'},
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'MI'},
    {'country': 'RU', 'state': null}
];
function sortFunc(a, b) {
    let val = a['country'] < b['country'];
    console.log(a['country'], b['country'], val);
    return +val;
}
data.sort(sortFunc);
console.log(data);

What is the issue with the above code?

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

0

The sort function needs to go both ways and return 0 if equal or -1 or 1 -- the above function just returns 1 or 0. Here would be a proper version:

let data = [
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'CA'},
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'MI'},
    {'country': 'RU', 'state': null}
];
function sortFunc(_a, _b) {
    let [a,b] = [_a['country'], _b['country']];
    if (a===b)      return 0;
    else if (a>b)   return 1;
    else            return -1;
}
data.sort(sortFunc);
console.log(data);

about 4 years ago · Juan Pablo Isaza Report

0

I don't know whether you want to sort it in ascending or descending, so just figure it out yourself from ternary operator. Rest I guess its working as you expect.

let data = [
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'CA'},
    {'country': 'AB', 'state': 'DE'},
    {'country': 'US', 'state': 'MI'},
    {'country': 'RU', 'state': null}
];
function sortFunc(a, b) {
    return a['country'] < b['country']?1:-1;
}
data = data.sort(sortFunc);
console.log(data);

enter image description here

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!