Reputation: 13329
How would you sort this array with these objects by distance
, so that you have the objects sorted from smallest distance to biggest distance?
[
{ distance: 3388, duration: "6 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
{ distance: 13564, duration: "12 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
{ distance: 4046, duration: "6 mins", from: "Lenchen Ave, Centurion 0046, South Africa" },
{ distance: 11970, duration: "17 mins", from: "Lenchen Ave, Centurion 0046, South Africa" }
]
Upvotes: 132
Views: 229239
Reputation: 164760
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
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.
Upvotes: 254