Sorting arrays in javascript by object key value

Use Array.prototype.sort(), eg

myArray.sort((a, b) => a.distance - b.distance)

The sort() method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and it’s job is to determine which of the two comes first.

It does this by returning an integer

  • Negative (less-than zero): The first argument comes first
  • Positive (greater-than zero): The second argument comes first
  • Zero: The arguments are considered equal for sorting

When you’re dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.

Leave a Comment