Calum Harris
Calum Harris

Reputation: 73

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

I need to get the index of the largest value in the array connections. This array is used to output values to a table, I need to be able to then set the cell in this table with the largest value to be red. Here is what I have so far:

cells[0].innerHTML = connections[0];
cells[1].innerHTML = connections[1];
cells[2].innerHTML = connections[2];
cells[3].innerHTML = connections[3];
cells[4].innerHTML = connections[4];
cells[5].innerHTML = connections[5];
cells[6].innerHTML = connections[6];
cells[7].innerHTML = connections[7];
cells[8].innerHTML = connections[8];
cells[9].innerHTML = connections[9];

cells[].style.backgroundColor = "red";

How would I go about finding the index of the biggest value in the connections array and setting the position of cells[] to it. I have tried using a loop and if statement to find the value but I then had trouble with getting that value out of the loop.

Upvotes: 0

Views: 101

Answers (4)

Mark Reed
Mark Reed

Reputation: 95242

You can get the maximum value by simply applying Math.max to the array. But if you want its index, you have to do a little more work.

The most straightforward approach is to do something like this:

connections.indexOf(Math.max.apply(Math, connections))

If you want to be more efficient (since that traverses the array twice), you can write your own reduction:

maxConnIndex = connections.reduce(function(curMax, curVal, curIdx) {
    let [maxVal, maxIdx] = curMax
    if (curVal > maxVal) {
      maxVal = curVal
      maxIdx = curIdx
    }
    return [maxVal, maxIdx]
  }, [connections[0],0])[1];

Upvotes: 1

Phrogz
Phrogz

Reputation: 303136

Simple-to-follow, efficient code:

function maxIndex(array) {
  var idx, max=-Infinity;
  for (var i=array.length;i--;) {
    if (array[i]>max) {
      max = array[i];
      idx = i;
    }
  }
  return idx;
}

Upvotes: 0

Bryant Makes Programs
Bryant Makes Programs

Reputation: 1694

You can use the following:

var largest_number = Math.max.apply(Math, my_array);
var largest_index = my_array.indexOf(largest_number);

Upvotes: 3

justyy
justyy

Reputation: 6041

var maxvalue = Math.max.apply(null, connections);
var maxvalueindex = connections.indexOf(maxvalue);

References: http://www.jstips.co/en/calculate-the-max-min-value-from-an-array/

Upvotes: 1

Related Questions