Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest number in array and its position

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.

like image 344
Ed T. Avatar asked Mar 16 '13 22:03

Ed T.


People also ask

How do you find the position of the largest element in an array?

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.

What is the smallest subscript in an array?

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


2 Answers

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.

like image 149
Guffa Avatar answered Oct 12 '22 04:10

Guffa


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);
like image 38
MattDiamant Avatar answered Oct 12 '22 04:10

MattDiamant