0

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?

1
  • 2
    You cannot subtract two strings… Commented Sep 10, 2021 at 8:18

1 Answer 1

-1

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.