Smallest number in array and its position
Just loop through the array and look for the lowest number:
var index = 0;
var value = temp[0];
for (var i = 1; i < temp.length; i++) {
if (temp[i] < value) {
value = temp[i];
index = i;
}
}
Now value
contains the lowest value, and index
contains the lowest index where there is such a value in the array.
One-liner:
alist=[5,6,3,8,2]
idx=alist.indexOf(Math.min.apply(null,alist))
You want to use indexOf
http://www.w3schools.com/jsref/jsref_indexof_array.asp
Using the code that you had before, from the other question:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
Array.min = function( array ){
return Math.min.apply( Math, array );
};
var value = temp.min;
var key = temp.indexOf(value);
Find the smallest value using Math.min
and the spread operator:
var minimumValue = Math.min(...temp);
Then find the index using indexOf
:
var minimumValueIndex = temp.indexOf(minimumValue);
I personally prefer the spread operator over apply
.