0

I am trying to sort an array based off the numeric value of one object in that array. So the current array I have is:

{opp_id: 123, latitude: "40.0467921", longitude: "-76.29504939999998", distance: 4.326332246421182}
{opp_id: 115, latitude: "39.9492628", longitude: "-76.69909960000001", distance: 24.81327544469476}
{opp_id: 66, latitude: "40.0467921", longitude: "-76.29504939999998", distance: 4.326332246421182}
{opp_id: 64, latitude: "37.7863453", longitude: "-122.44204609999997", distance: 2464.2610167173516}

What I want to do is to then sort this array based off the 'distance' object by smallest number to largest number. Is there a Javascript function that could do this?

Logan C
  • 55
  • 5

1 Answers1

0

Use sort like below.

x=[{opp_id: 123, latitude: "40.0467921", longitude: "-76.29504939999998", distance: 4.326332246421182},
{opp_id: 115, latitude: "39.9492628", longitude: "-76.69909960000001", distance: 24.81327544469476},
{opp_id: 66, latitude: "40.0467921", longitude: "-76.29504939999998", distance: 4.326332246421182},
{opp_id: 64, latitude: "37.7863453", longitude: "-122.44204609999997", distance: 2464.2610167173516}]

console.log(x.sort((a,b)=>a.distance-b.distance))
yajiv
  • 2,901
  • 2
  • 15
  • 25