0

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.

Bryant Makes Programs
  • 1,493
  • 2
  • 17
  • 39
Calum Harris
  • 63
  • 10
  • 1
    Possible duplicate of [JavaScript: min & max Array values?](http://stackoverflow.com/questions/1669190/javascript-min-max-array-values) – MatthieuLemoine Jan 04 '17 at 16:23

4 Answers4

3

You can use the following:

var largest_number = Math.max.apply(Math, my_array);
var largest_index = my_array.indexOf(largest_number);
Bryant Makes Programs
  • 1,493
  • 2
  • 17
  • 39
1
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/

justyy
  • 5,831
  • 4
  • 40
  • 73
1

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];
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • Sorry if it was unclear, not the best at explaining these sorts of things, but yes i wanted the index of the largest value. The answer above seems to have worked correctly but thanks anyway :) – Calum Harris Jan 04 '17 at 16:36
0

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;
}
Phrogz
  • 296,393
  • 112
  • 651
  • 745