I have a form where the user enters their city, this then returns for all the cities where my client is based in a 30 mile radius. I am now trying to find the closest city out of these and return just one result with both City Name and Distance (in metres).
I have a for loop which processes my results:
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
//console.log(response);
for (var j = 0; j < results.length; j++) {
// If distance is less than 30 miles (48280 metres)
if(results[j].distance.value < 48280) {
var closestCitiesDist = results[j].distance.value
var closestCitiesName = origins[i]
var closestCities = {"cityName" : closestCitiesName, "cityDistance" : closestCitiesDist}
console.log(closestCities);
}
}
}
This now returns an array for each result, containing cityName and cityDistance variable. Out of each of these arrays, I would like to find the single closest city (the array with the smallest cityDistance), and be able to output "City xx is the closest (xxx metres away)"
You could use Array#sort which has a time complexity of O(n log n) or instead you could do a single backwards pass of bubble sort in O(n), to bring the smallest city to the front of the array.
const object = [
{ cityName: 'Vancouver', cityDistance: 3 },
{ cityName: 'Paris', cityDistance: 4 },
{ cityName: 'London', cityDistance: 1 },
];
for (let i = object.length - 1; i > 0; i--) {
if (object[i].cityDistance < object[i - 1].cityDistance) {
temp = object[i - 1];
object[i - 1] = object[i];
object[i] = temp;
}
}
console.log(
`City ${object[0].cityName} is the closest (${object[0].cityDistance} metres away)`
);
You use Array.prototype.sort() on an array of objects, and sort it as you wish
Reference Material: Array.prototype.sort
Here element at the 0 index will have the smalles value property
const object = [{ name: 'test', value: 3}, { name: 'test2', value: 1}];
const sorted = object.sort((a, b) => a.value - b.value);
console.log(sorted);