Javascript Program to Sort the given array of objects having lat, lng by distance from your given location.

Yogesh Nogia
2 min readJun 3, 2020

When I was preparing for my javascript interviews, I came across a very interesting question, simple yet very useful when dealing with Google Maps API.

Question: Sort the given array of objects by distance(using lat, long) from your given location.

Your Location:

const locationObject = {   name: "Yogesh Nogia",   latitude: "28.535517",   longitude: "77.391029",}

An Array of objects:

const arrObject = [{   name: "Abhishek", latitude: "26.449923", longitude: "80.331871",},{   name: "Akhtar", latitude: "27.167641", longitude: "27.167641"},{   name: "Raj", latitude: "28.632429", longitude: "77.218788",},{   name: "Ravi", latitude: "25.435801", longitude: "81.846313",}]

There are many ways to solve this question and sort the array but the first thing we need here is every node distance between Your location to Array elements.

To find the distance using lat lng between two points, we`ll create this function:

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {   var R = 6371; // Radius of the earth in km   var dLat = deg2rad(lat2-lat1);  // deg2rad below   var dLon = deg2rad(lon2-lon1);   var a =   Math.sin(dLat/2) * Math.sin(dLat/2) +   Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *   Math.sin(dLon/2) * Math.sin(dLon/2);   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));   var d = R * c; // Distance in km   return d;  // distance returned}function deg2rad(deg) {   return deg * (Math.PI/180)}

Function getDistanceFromLatLonInKm takes four arguments i.e. 2 lat & lngs. We`ll pass the first lat lng from locationObject and second one from each element of an array

for(let i = 0; i<arrObject.length; i++) {   let distance = getDistanceFromLatLonInKm(parseInt(locationObject.latitude), 
parseInt(locationObject.longitude),arrObject[i].latitude,
arrObject[i].longitude);
//Attaching returned distance from function to array elements arrObject[i].distance = distance;}console.log(arrObject); // [{... distance: ...}]

We now have distance value in our arrObject. So, we can now sort it using simply sort method of JavaScript.

arrObject.sort(function(a, b) {
return a.distance - b.distance
});
console.log(arrObject); //sorted array from Your locationObject

There you go! Thanks for reading this. This is my first article on Medium. Hope you liked it.

--

--

Yogesh Nogia

Fond of technology. Professional Coder. Human inside.