What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:
temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.
To find the largest element, the first two elements of array are checked and the largest of these two elements are placed in arr[0] the first and third elements are checked and largest of these two elements is placed in arr[0] . this process continues until the first and last elements are checked.
#1) lbound: This is the opposite of ubound (used above). This returns the smallest integer index value of an array i.e. the smallest subscript of an array.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With