Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the array key with the highest value in javascript

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?

like image 910
Alexa Avatar asked May 01 '11 19:05

Alexa


1 Answers

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...

like image 98
kennebec Avatar answered Oct 10 '22 04:10

kennebec