Alex Rivera | Logout

Get the array key with the highest value in javascript

Asked 2011-05-01T19:58:42.760
13

I have a array like

arr[1] = 234;
arr[2] = 345;
...

arr[40] = 126;

How can I get the index of the element with the highest value without reiterating the array?

Edit
Report

2 Answers

19

You can apply Math.max and pass the array as its arguments-

arr.indexOf(Math.max.apply(window,arr))

But now Math.max is doing the iterating, just as sort would do.

Somebody has to look at each item in an unsorted array...

answered 2011-05-01T23:18:00.877
2

You could use a function to set the variable. And keep track of the max in that function. Here's a quick example without type checking, testing, or support for removing a value.

Array.prototype.maxValue = null;

Array.prototype.setIndex = function(index, value){
  this[index] = value;
  if (value > this.maxValue || this.maxValue == null)
    this.maxValue = value;
}


var arr = new Array();
arr.setIndex(0, 234);
arr.setIndex(1, 500);
arr.setIndex(2, -5);

var maxValue = arr.maxValue;

Obviously this is nicer if you're currently setting items like this:

var arr = new Array();
arr[0] = 1;
arr[1] = 500;
arr[2] = 2;

Rather than this:

var arr = { 1, 500, 2 };

The downside is its not natural and requires you to use function to get the correct results.

answered 2011-05-01T20:06:15.317

Your Answer