You must ensure that the array is spread out to obtain the maximum value. Otherwise, if you try to access it directly as a stringed array, you will get NaN
, which is not part of the array and cannot be searched.
When you spread the array, all its elements are used as parameters for the function (see spread syntax ...
).
In this scenario, the operation looks like this:
Math.max(...[11, 10, 10])
will be computed as
Math.max(11, 10, 10)
function sayHello() {
arrayEdificiosNiveis = [11, 10, 10];
var indexMenor = arrayEdificiosNiveis.indexOf(Math.max(...arrayEdificiosNiveis));
console.log(indexMenor);
}
sayHello();
A concise solution using a single loop:
However, why not utilize
v > a[r] ? i : r
(which seems more intuitive) instead of
v <= a[r] ? r : i
The issue arises from the initial comparison with the element at index zero. At that point, r = -1
and the element is a[r] = undefined
.
Comparing with undefined
using a relational operator such as <
, <=
, >
, or >=
always returns
false</code, resulting in the incorrect index of <code>-1
instead of zero. This error persists for every other element in the array.
const
getFirstIndexOfMaxValue = array =>
array.reduce((r, v, i, a) => v <= a[r] ? r : i, -1);
console.log(getFirstIndexOfMaxValue([]));
console.log(getFirstIndexOfMaxValue([11]));
console.log(getFirstIndexOfMaxValue([11, 10]));
console.log(getFirstIndexOfMaxValue([11, 10, 10]));
console.log(getFirstIndexOfMaxValue([10, 11, 10]));
console.log(getFirstIndexOfMaxValue([10, 11, 10, 11]));