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.

1

4 Answers 4

3

You can use the following:

var largest_number = Math.max.apply(Math, my_array);
var largest_index = my_array.indexOf(largest_number);
Sign up to request clarification or add additional context in comments.

5 Comments

But what about the index?
my apologies, had forgotten the index. adjusted my answer.
Will add as answer when It allows me :)
Thanks for the edit, I see i missed that out. Makes more sense now. Thanks again :)
Note that this answer is ~2x as slow as it needs to be, since it has to iterate over the list once fully and then again to find the index.
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/

Comments

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];

1 Comment

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 :)
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.