Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Sort JavaScript Object Arrays by a Property Value

1 min read .
Sort JavaScript Object Arrays by a Property Value

JavaScript comparator functions make it straightforward to sort arrays of objects by a numeric property.

const data = [
  { name: 'Edward', order: 21 },
  { name: 'Sharpe', order: 37 },
  { name: 'And', order: 45 },
  { name: 'The', order: -12 },
  { name: 'Magnetic', order: 13 },
  { name: 'Zeros', order: 37 },
];

Descending Order

const sorted = data.toSorted((a, b) => b.order - a.order);

This places the largest order value first.

Ascending Order

const sorted = data.toSorted((a, b) => a.order - b.order);

sort() Mutates the Array

The traditional sort() method changes the array in place:

data.sort((a, b) => a.order - b.order);

Use toSorted() when you want to preserve the source array. For older runtimes, clone first:

const sorted = [...data].sort((a, b) => a.order - b.order);

Sorting Strings

For human-readable strings, use localeCompare rather than subtraction:

const byName = data.toSorted((a, b) => a.name.localeCompare(b.name));

Conclusion

Provide a comparator that expresses the order you want. Use numeric subtraction for numeric fields, localeCompare for strings, and prefer toSorted() when mutation would be undesirable.

Related Posts

chevron-up