— 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.
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 :
-
You wrote a loop that can be replaced with the map function. This is basically what your wrote but in a longer fashion.
-
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])