Appel
Appel

Reputation: 497

Sort an array based on value

What is the most effective way to sort an array based on a value. I have variable user_location_lat and a user_location_long togheter with the array store_locations.

My variable user location has (for example) this value: lat 45.222123123/long 54.5589858 the array look like this:

id: 4, lat: 43.22243243, longi: 52,342234
id: 5, lat: 45.22243243, longi: 65,432432
id: 8, lat: 77.22243243, longi: 77,555324

etc.

I know how I can sort an array based on the values inside the array. But not how I can sort them based on a value outside the array.

How can I find the nearest value from the array by user_location?

EDIT: And is it possible to get the closest location based on lat and long? See my edit above.

Upvotes: 0

Views: 198

Answers (1)

Brad
Brad

Reputation: 8698

var latArray = [43.22243243, 45.22243243, 77.22243243]
var myLat = 45.222123123;

var closest = latArray.reduce(function (prev, curr) {
  return (Math.abs(curr - myLat) < Math.abs(prev - myLat) ? curr : prev);
});

console.log(closest);

source: get closest number out of array

Upvotes: 1

Related Questions