d
Amit DhamuSoftware Engineer
 

Sort Array of Objects by Property

1 minute read 00000 views
const sortArrayOfObjectsByProperty = (array, property, direction = 'asc') => {
  const operators = {
    '>': (a, b) => a > b,
    '<': (a, b) => a < b,
  }

  let operator = operators['>']
  direction = direction.toLowerCase()

  if (direction === 'desc') {
    operator = operators['<']
  }

  return array.sort((a, b) => {
    if (operator(a[property], b[property])) {
      return 1
    }
    if (operator(b[property], a[property])) {
      return -1
    }
    return 0
  })
}