— 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’.
3
Answers
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.
You can simply do it, using
Array#reduce()
method with a one liner code:This way you can avoid using
Math.max()
and multiple iterations.Demo:
You could introduce a helper that returns an item of a collection based on the highest value.
The above function iterates through an iterable. For each item it executes the
fnValue
function to get a value. It then compares the value against the highest value found so far. If it’s less than or equal to the max value, it will go to next item. Otherwise the max item and value will be replaced with the current item and value.Note that comparisons with
undefined
always evaluate tofalse
. So the first iteration500 <= undefined
will producefalse
, thus setting themaxItem
andmaxValue
.This would allow you to do the following: