Sorting arrays in javascript by object key value

How would you sort this array with these objects by distance. So that you have the objects sorted from smallest distance to biggest distance ?

Object { distance=3388, duration="6 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

Object { distance=13564, duration="12 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

Object { distance=4046, duration="6 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

Object { distance=11970, duration="17 mins", from="Lenchen Ave, Centurion 0046, South Africa", more...}

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.


here's an example with the accepted answer:

 a = [{name:"alex"},{name:"clex"},{name:"blex"}];

For Ascending :

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

output : [{name: "alex"}, {name: "blex"},{name: "clex"} ]

For Decending :

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

output : [{name: "clex"}, {name: "blex"}, {name: "alex"}]