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

114
Views
Array of object not sorting on a key

I have the following array of objects that I want to order by name key. For some reason if I try to sort by the "name" key it doesn't sort. If I sort by a "price_value" key it works .

let arr = [
  {
    "name": "Road Bike",
    "slug": "road-bike",
    "price_value": 2499
  },
  {
    "name": "Laptop",
    "slug": "laptop",
    "price_value": 1299,
  },

];

let br = [...arr].sort((a, b) => a.name - b.name)[0].name;

console.log(br) //should be Laptop, even if you try to sort on slug key doesn't work

I always get Road Bike as first element. If I try to sort on price_value key it works normally.

let br = [...arr].sort( (a,b) => a.price_value - b.price_value )[0].name;
console.log( br ) //It's Laptop as expected

Where is the problem?

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

0

You cannot subtract string. a.name - b.name is not a valid operation and returns NaN.

It should work if you do:

let br = [...arr].sort((a, b) => a.name.localeCompare(b.name))[0].name;
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!