0

I am trying to sort an array by names in alphabetic order, with numbers it works, but with names doesn't. Why?

var arr = [{
    name: 'Thomas',
    age: 19
  },
  {
    name: 'Noé',
    age: 17
  },
  {
    name: 'Andrey',
    age: 27
  },
  {
    name: 'Luc',
    age: 20
  }
]

const res = arr.sort((e1, e2) => e1.name - e2.name)

console.log(res)

1
  • e1.name - e2.name are you trying to subtract two strings? What do you except it to return? Commented Feb 27, 2021 at 7:14

1 Answer 1

1

Strings may not be subtracted, but you can compare them using localeCompare

const res = arr.sort((e1, e2) =>
  e1.name.toLowerCase().localeCompare(e2.name.toLowerCase())
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.