15

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.

Eugen Sunic
  • 12,218
  • 8
  • 60
  • 78
Ed T.
  • 979
  • 2
  • 9
  • 17

7 Answers7

15

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.

Guffa
  • 666,277
  • 106
  • 705
  • 986
7

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);
MattDiamant
  • 8,010
  • 4
  • 35
  • 45
7

One-liner:

alist=[5,6,3,8,2]

idx=alist.indexOf(Math.min.apply(null,alist))
Bugs
  • 4,456
  • 9
  • 32
  • 40
Tony
  • 113
  • 1
  • 3
2

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.

sporklpony
  • 369
  • 4
  • 15
1

See this answer of "find max" version of this question. It is simple and good. You can use the index to get the element afterward.

Vasyl Lyashkevych
  • 1,734
  • 2
  • 21
  • 35
Raku Zeta
  • 21
  • 4
1

You could use reduce, and compare against Infinity.

let minIndex = -1;
arr.reduce((acc, curr, index) => {
    if (curr < acc) {
        minIndex = index;
        return curr;
    } else {
        return acc;
    }
}, Infinity);
ruohola
  • 19,113
  • 6
  • 51
  • 82
Apollo
  • 1,734
  • 2
  • 17
  • 26
0

Here is a solution using simple recursion. The output is an object containing the index position of the min number and the min number itself

const findMinIndex = (arr, min, minIndex, i) => {
  if (arr.length === i) return {minIndex, min};
  if (arr[i] < min) {
    min = arr[i]
    minIndex = i;
  }
  return findMinIndex(arr, min, minIndex, ++i)

}

const arr = [5, 5, 22, 11, 6, 7, 9, 22];
const minIndex = findMinIndex(arr, arr[0], 0, 0)
console.log(minIndex);
Eugen Sunic
  • 12,218
  • 8
  • 60
  • 78