0

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.

Appel
  • 497
  • 5
  • 13
  • You need to first loop through the array of objects and calculate the distance to the `user_location` and add it as a property of the object. Then `sort()` the array by that property – Rory McCrossan Mar 06 '17 at 14:48
  • How do you store the id related to the value in your array? – Oliver F. Mar 06 '17 at 14:49

1 Answers1

1

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

Community
  • 1
  • 1
Brad
  • 8,044
  • 10
  • 39
  • 50
  • Thanks, but I've made a mistake in my code. I need to closest lat and long (see my post), is that possible? I thought lat only was enough in this situation.. but it isn't, sorry! – Appel Mar 06 '17 at 16:18
  • 1
    maybe check out this: http://stackoverflow.com/questions/17594401/find-closest-city-to-given-longitude-latitude – Brad Mar 06 '17 at 16:21