What is the best way to find the maximum and minimum values within a nested array in JavaScript?

I am looking to extract the highest and lowest values from specific data points within a nested array.

For example, this nested array is structured as [latitude, longitude].

The specific nested array in question looks like this: [[40, 50], [50, 60], [60, 70]].

When it comes to longitude, the maximum value should be 70 and the minimum should be 50.

As for latitude, the maximum value should be 60 and the minimum should be 40.

To find the average longitude value, you should get 60, while for average latitude it would be 50.

So my query now is how can I use JavaScript to identify the maximum and minimum longitude and latitude values separately within the nested array, and then calculate their averages?

Answer №1

How about trying out the code snippet below:

var elements = [[3, 9], [5, 7], [8,12]];
// Finding the maximum value for index 0
Math.max.apply(Math, elements.map(function(item) { return item[0]; }));
8
// Finding the maximum value for index 1
Math.max.apply(Math, elements.map(function(item) { return item[1]; }));
12
// Finding the minimum value for index 0
Math.min.apply(Math, elements.map(function(item) { return item[0]; }));
3
// Finding the minimum value for index 1
Math.min.apply(Math, elements.map(function(item) { return item[1]; }));
7

I hope this solution works for you.

Answer №2

const coordinates = [[40, 50], [50, 60], [60, 70]]

const latitude = coordinates.map(a => a[0])
const longitude = coordinates.map(a => a[1])

const maxLatitude = Math.max(...latitude)
const minLatitude = Math.min(...latitude)
const avgLatitude = (latitude.reduce((acc,cur) => acc + cur, 0))/latitude.length
console.log(maxLatitude, minLatitude, avgLatitude)

const maxLongitude = Math.max(...longitude)
const minLongitude = Math.min(...longitude)
const avgLongitude = (longitude.reduce((acc,cur) => acc + cur, 0))/longitude.length
console.log(maxLongitude, minLongitude, avgLongitude)

Answer №3

By utilizing the Array#reduce technique, you can accomplish this task in a more "functional" manner.

The process starts by setting an initial value from the input array and then proceeds to scan through the array to identify and update the current minimum or maximum values as it progresses.

Expanding on this method, the "average" functions are created by combining both the "minimum" and "maximum" functions, followed by computing the average of the numerical results:

var array = [[40, 50], [50, 60], [60, 70]]

const findMinLatitude = (arr) => {

  return arr.reduce((min, item) => {
    
    return Math.min(min, item[0])
    
  }, arr[0][0])
}

const findMaxLatitude = (arr) => {

  return arr.reduce((max, item) => {
    
    return Math.max(max, item[0])
    
  }, arr[0][0])
}

const findAvgLatitide = (arry) => {
  
  return (findMinLatitude(arry) + findMaxLatitude(arry)) * 0.5
}

const findMinLongitude = (arr) => {

  return arr.reduce((min, item) => {
    
    return Math.min(min, item[1])
    
  }, arr[0][1])
}

const findMaxLongitude = (arr) => {

  return arr.reduce((max, item) => {
    
    return Math.max(max, item[1])
    
  }, arr[0][1])
}

const findAvgLongitude = (arry) => {
  
  return (findMinLongitude(arry) + findMaxLongitude(arry)) * 0.5
}

console.log('Min latitude', findMinLatitude(array))
console.log('Max latitude', findMaxLatitude(array))
console.log('Average latitude', findAvgLatitide(array))
console.log('Min longitude', findMinLongitude(array))
console.log('Max longitude', findMaxLongitude(array))
console.log('Average longitude', findAvgLongitude(array))

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

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

Unable to process form submission with AngularJS + Stormpath

I am facing an issue with form submission. Even though I believe that the login and password data are being sent correctly, nothing happens when I submit the form. I am attempting to submit the form without using ngSubmit because it is not feasible in my s ...

The ideal formats for tables and JavaScript: How to effectively retrieve arrays from a table?

Given the task of defining a function that extracts the mode of weights from an HTML table containing age and weight data for individuals within a specified age range. The function needs to be able to handle tables of any size. I am looking for the most ef ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

MTG Life counter. Display fluctuations in count

I am currently working on a fun project creating an MTG (Magic The Gathering) life tracker, even though the code is quite messy. Despite its flaws, it still gets the job done. Click here to view the MTG life tracker https://i.stack.imgur.com/Su17J.png ...

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

Encountering an issue with foreach loop that is continuously providing me with a

Here is the situation: foreach ($country as $value){ After using print_r on the contents of $country, I see this: Array But, when I print_r all POST variables, it shows country as a single array instead of an array within an array as shown above? Arra ...

Ways to programmatically open a new tab in VueJs without requiring a button click

After receiving a successful response from Axios, I would like to open the page link in a new tab. I have searched for a solution online, but the browser is consistently blocking popups. The code below worked for me, however it is not supported in all brow ...

What could be causing the DATE_SUB function to fail in executing a MySQL query through Node.js?

I am encountering an issue with a datetime field in a MySQL database table on Planetscale. My goal is to subtract some time from the datetime value using the DATE_SUB function. While this operation works smoothly in the database console on Planetscale&apos ...

Does Firestore arrayunion offer any kind of callback function?

Hey there! I'm currently working on a voting system and I want to prevent the same user from voting multiple times on the same post. let db = firebase.firestore(); var postRef = db.collection("posts").doc(this.pid); postRef.update({ ...

Is there a way for me to convert this JSON object back into a string?

Presently, I possess this specific JSON object "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "homeworld": "Tatooine", "films": [ "A N ...

Verify if items in a list contain a source from a variable and then execute code - jQuery / JavaScript

My goal is to compare the variable SRC to the image sources in a list from my HTML. If it matches, I want to execute a specific function. Unfortunately, it appears that this process is not functioning correctly. For a live example, please visit the follow ...

What causes data to update in a Vue template but not in the JavaScript portion of the code?

The topic in the template section updates when its value in the parent component changes, however, the same value in the script part remains the initial value it received at search_params.set('param1', this.topic);. Everything else in the code is ...

How can I use ReactJS to find the nearest five locations in order from closest to farthest?

I'm in the process of creating a website for searching nearby locations. I am facing an issue where I want to display the 5 closest locations from my current location in ascending order, but I keep getting the same location result. I need these locati ...

Parsing JSON into a List of Objects

Here is a filter string in the following format: {"groupOp":"AND","rules":[{"field":"FName","op":"bw","data":"te"}]} I am looking to deserialize this into a Generic list of items. Any tips on how I can accomplish this? ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

HTML comments generated from Freemarker's list notation

Currently, I have integrated Apache Freemarker into an HTML editor where users can create templates using code. For example, a user may write the following code for a list: <#list items as item>...</#list> While this is the correct way to gen ...

NextJS: When attempting to serialize the `function` as JSON, an error occurs as it is not a JSON serializable data type

In my Firestore database, I have a collection named "mentor" that contains documents with three fields: "name", "email", and "linkedin". My goal is to fetch all the documents from this collection and pass them as props so that I can render their fields on ...

Is it possible to navigate to the Next page using a different button instead of the pagination controls

Is it possible to navigate to the next page upon clicking a button labeled "Press me"? Here is the code snippet: <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/an ...