I am currently working on a JavaScript challenge: I have an array of random map coordinates (latitude, longitude) stored like this:
var coordinates = [
[64,22],[55,33],[28,35],[...,...]
]
Additionally, I have a function that calculates the distance between two points:
For example:
var getDistance = function(point1, point2)
{
return L.dist(point1, point2); //using Leaflet method
}
Here is where I'm struggling:
How can I rearrange my array to sort the distances by closest proximity from the first coordinate, then from the second, third, and so on? Does anyone have a solution for this? I feel stuck :(
edit 1 :
I attempted to tackle the issue with a nested loop, but the results are not as expected.
var closestIndex = 1;
var closestDistance = 99999999;
for (var i = 0; i < coords.length; i++) {
for (var j = i + 1; j < coords.length; j++) {
if ((Map().distance(coords[i], coords[j]) < closestDistance) &&
(Map().distance(coords[i], coords[j]) != 0)) {
closestDistance = (Map().distance(coords[i], coords[j]));
closestIndex = j;
}
}
console.log("CD", closestDistance + "(" + closestIndex + ")");
finalArray.push(coords[closestIndex]);
coords.splice(closestIndex, 0);
cloestDistance = 9999999;
}