Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of the min value in an array using JavaScript?

I wrote this function, which returns -1.

function sayHello() {
  let arrayEdificiosNiveis = [11,10,10];
  var indexMenor = arrayEdificiosNiveis.indexOf(Math.max(arrayEdificiosNiveis));
  console.log(indexMenor);
}
sayHello();

I expected 0, not -1. How do I solve this problem?

like image 332
Miguel Rodrigues Avatar asked Apr 14 '19 15:04

Miguel Rodrigues


2 Answers

You need to spread the array for getting the maximum. Otherwise you get NaN as value (via a stringed array) and this is not in the array (and not searchable).

A spreaded array takes all elements as parameter for the function (spread syntax ...).

In this case it follows this way

Math.max(...[11, 10, 10])

is evaluated as

Math.max(11, 10, 10)

function sayHello() {
  arrayEdificiosNiveis = [11, 10, 10];
  var indexMenor = arrayEdificiosNiveis.indexOf(Math.max(...arrayEdificiosNiveis));
  
  console.log(indexMenor);
}

sayHello();

A single loop solution:

But why not use

v > a[r] ? i : r

(which feels more natural, sort of) instead of

v <= a[r] ? r : i

The problem is the first comparison with the first element at index zero. at this time, r = -1 and the element is a[r] = undefined.

A comparison with undefined and a relational operator of <, <=, > or >= is always false and that would return the wrong index of -1 instead of zero and this result does not change for any other element of 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]));
like image 194
Nina Scholz Avatar answered Oct 05 '22 10:10

Nina Scholz


The problem in your approach is the complete array you're passing on the function Math.max:

const arrayEdificiosNiveis = [11, 10, 10],
  max = Math.max(...arrayEdificiosNiveis);
  
console.log(arrayEdificiosNiveis.findIndex(elem => elem === max));

If it's not possible to use Spread syntax, you can call the function apply which receives an array as the parameters of function Math.max

function sayHello() {
  const arrayEdificiosNiveis = [11, 10, 10],
    max = Math.max.apply(null, arrayEdificiosNiveis),
    indexMenor = arrayEdificiosNiveis.indexOf(max);
  console.log(indexMenor);
}
sayHello();
like image 30
Ele Avatar answered Oct 05 '22 10:10

Ele