Get the element in a javascript array that has the smallest value

I have a collection of cities each with a "distance" value

ajax = new Location('123 main street', 'city, ON', 'L9Z 0K5', '905-555-5555', '905-555-555', 43.864362, -79.011627, 6);
alliston = new Location('117 Young Street', 'place, ON', 'L5R 0E9', '705-555-1234', '705-444-4321', 44.147691, -79.884193, 15);
aurora = new Location('2 New Place', 'capitol, ON', 'L8G 3W8', '905-999-0155', '905-727-5678', 44.009139, -79.470980, 1);
brampton = new Location('50 Circle Cres.', 'wendy, ON', 'L9r 8S1', '905-888-8888', null, 43.680537, -79.714164, 25);

All these location objects (where the last key is distance) are stored in an array named cities

Is there a way for me to cycle through this array and display the object with the smallest distance?

Answer №1

cities.reduce(function(a, b) {
 return (b.distance < a.distance)  ? b : a;
})

||

cities.sort(function(x, y) {
 return x.distance - y.distance;
})[0]

Answer №2

To find the nearest location, you can utilize the `reduce` method of the `Array`. Assuming your `Location` object includes a `distance` property:

var nearest = [ajax,alliston,aurora,brampton]
    .reduce( function( nearest, location ) { 
        return !nearest || location.distance < nearest.distance 
            ? location : nearest;
    } );

It is worth noting that iccthedral's approach to using `reduce` is more concise than mine, as he cleverly takes advantage of `reduce`'s behavior when not providing an initial value. As stated in MDN: "If no initialValue was provided, then will be equal to the first value in the array."

Answer №4

To implement sorting with an array object, you can utilize the arrayObject.sort(sortby) method and specify your custom sortby function (for example, by returning loc_a.distance - loc_b.distance).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert epoch time to HHMM format using JavaScript

I have a specific variable that stores epoch time data. My goal is to showcase the time information in HHMM format. Below you can find the code I am currently using; function convertEpochTimeToDateObj(epoch_time) { var utcSeconds = epoch_time; va ...

Building blocks & lists in markup language

I've created my constructor and array, but I'm unsure how to display it in the HTML file. It involves a plus/minus show/hide feature. Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Customize the Color of the Selected Button on the Menu (Implementing Ant Design Components in React)

Hello, I am reaching out to inquire about the process of updating the menu associated with a specific button in Ant Design using React. I am interested in changing the options that are displayed when the button is clicked. I would greatly appreciate any g ...

What is the architecture of Facebook's database for managing posts and comments?

Looking to create a basic social networking site and curious about how Facebook manages comments on posts. Do they store Posts and their comments in the same database table row, or do they have separate tables for each post? Seeking advice on what would b ...

Display and conceal elements within predetermined time intervals using jQuery, while ensuring that the final element remains visible

Is there a way to automatically hide div1 and show div2 after a set amount of time, let's say 10 seconds or 15 seconds? I came across this thread: Show and hide divs at a specific time interval using jQuery, However, the solution provided in the po ...

What is the best way to include a class multiple times in a render method?

I'm currently working on a React project and have the following code snippet. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</t ...

Encountering ECONNREFUSED error when making requests to an external API in a NextJS application integrated with Auth

Currently, I have integrated Auth0 authentication into my NextJS application by following their documentation. Now, I am in the process of calling an external ExpressJS application using the guidelines provided here: https://github.com/auth0/nextjs-auth0/b ...

Using Backbone.js to Retrieve Data from the Server and Bind it to a Model

Having recently delved into Backbone.js, I found this informative tutorial quite helpful in getting started. Now, I am looking to take things a step further by fetching data from the server instead of hardcoding values in JavaScript as demonstrated in the ...

What is the best way to use Javascript to append a class to a dynamically generated child item in a Joomla menu, specifically within a designated div?

Currently, I'm in the process of designing a template using Bootstrap 4 specifically for Joomla 4. The menu structure on different levels such as parent, child, and deeper, is defined within the mod_menu php files. I've implemented the same main ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

Tips for deploying a Vue.js website on IONOS?

I recently created a website using vue and found myself in need of uploading it online. Despite feeling unsure, I decided to go with IONOS since it was recommended by Google. However, I am currently facing challenges trying to upload my site as the proce ...

Locating the maximal value within a column of an array

This is the code from the first source file. #include<stdio.h> void main(void) { extern int transitTime[]; int time1; int i,j; int largest; printf("Please enter the time you left school.\n"); scanf("%d",&time1); ...

What factors outside of the program could potentially lead to the splice function not functioning as expected?

Within my code, I encountered a peculiar issue involving a splice line along with debug lines on both sides. Take a look: const obj = { x:[1,2], y:{t:"!!!"} } const lenBefore = S.groupings.length const ret = S.groupings.splice(gix, 0, obj) console.log(`${ ...

The source property in the Nextjs Image tag is not valid

<Image src={"http://localhost:3000/images/img.jpeg"} layout="fill" objectFit="cover" width={"100%"} height={"100%"} /> An error message has appeared: https://i.sstatic.net/jI9mh.png Any s ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

Check if the string contains any numerical characters

Is there a way to check if a string contains at least one numerical character without verifying if the entire string is a number? The current code works in the following situations: If there is a single integer, such as "43", it will display the correspon ...

Distinguishing among ArrayList declarations

While researching online, I came across an interesting declaration for an ArrayList: ArrayList[] graph = new ArrayList[numCourses]; This was contrary to what I knew, as I had always seen ArrayList declared as: ArrayList<type> graph = new ArrayList ...

What is the best way to choose a specific word in a single row from a column that contains an array?

I need to filter a column that stores arrays of strings based on a specific keyword. However, when I attempt to do this, I encounter the following error: function contains(character varying[], unknown) does not exist Below is the query I am using: SELECT ...