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)
JohnPix
  • 1,595
  • 21
  • 44
  • `e1.name - e2.name` are you trying to subtract two strings? What do you except it to return? – Lab Feb 27 '21 at 07:14

1 Answers1

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())
);
greenBox
  • 552
  • 4
  • 5