Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find largest number in multidimensional array

— My question concerns an array, not an object, which the similar question is for —

I have a multidimensional array, where I need to find the array with the largest number from a set position, then return the first item of that array.

I have this working, but feel there must be a better way to acheive this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code, which is working in testing:

slidesArray = [["1",500],["2",750],["3",501]];

var EmpArr = []
var x = 0;
var len = slidesArray.length;
for (x; x < len; x++) {
    EmpArr.push(Math.max(slidesArray[x][1]))
}

var largestResult = Math.max(...EmpArr);

var result = slidesArray.filter(function(v,i) {
    return v[1] === largestResult;
}); 

In this example, I need to check slidesArray[0][1], slidesArray[1][1] and slidesArray[2][1] to find which is the largest number. Then I want to return the first element of the array which contains the largest, so here ‘2’.

>Solution :

  1. You wrote a loop that can be replaced with the map function. This is basically what your wrote but in a longer fashion.

  2. You use filter but you want to find 1 result so the function ‘find’ is more suitable.

const slidesArray = [["1",500],["2",750],["3",501]];

// Map an array with second entries only, then get the maximum value
let max = Math.max(...slidesArray.map(entry => entry[1]))

// Find entry with max value
let result = slidesArray.find(entry => entry[1] === max)

// Show result
console.log(result[0])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading