Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Find Smallest Number from javascript object

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)"

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)`
);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!