Logo

TODAY I LEARNED

Sort an array of objects by a property value

Imagine that we have the next object:

const names = [
  { name: 'Sam', lastName: 'Belmor'},
  { name: 'Yasser', lastName: 'Velasco' },
  { name: 'Ayrton', lastName: 'Morales' }
]

If we wanna sort those values alpabethically by name we could do this:

names.sort((a, b) => (a.name > b.name) ? 1 : -1)

We'll have this result:

[
  { name: 'Ayrton', lastName: 'Morales' },
  { name: 'Sam', lastName: 'Belmor' },
  { name: 'Yasser', lastName: 'Velasco' }
]

If return 1, the function communicates to sort() that the object b takes precedence in sorting over the object a. Returning -1 would do the opposite.

Learned by samantha-bello on Nov 16, 2021

973983 adforcodereview v3 0211021 c02 021121