ThePinkHipo
ThePinkHipo

Reputation: 19

Javascript Find Lowest Number and its key

So if I have [2,3400,500,6,710] I want to find the lowest which would be 2 and its key which would be 0.

Before I was using Math.min.apply( Math, array ) but now I want to also get the key. Any ideas?

Upvotes: 1

Views: 230

Answers (2)

RobG
RobG

Reputation: 147403

xdazz's answer does the job, you can also do:

var a = [2, 3400, 500, 710];
var lowValue = a.concat().sort(function(a, b){return a - b})[0];
var lowIndex = a.indexOf(lowValue);

Note that Array.prototype.indexOf is ES5 so provide support for browsers that don't have it.

Upvotes: 1

xdazz
xdazz

Reputation: 160843

Use .indexOf

var array, min, index;
array = [2,3400,500,6,710];
min = Math.min.apply(null, array );
index = array.indexOf(min);

Upvotes: 5

Related Questions