19

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.

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
Ed T.
  • 1,039
  • 2
  • 11
  • 17

7 Answers7

17

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
  • 687,336
  • 108
  • 737
  • 1,005
8

One-liner:

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

idx=alist.indexOf(Math.min.apply(null,alist))
Bugs
  • 4,491
  • 9
  • 32
  • 41
Tony
  • 131
  • 1
  • 3
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,561
  • 4
  • 37
  • 46
3

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.

sporkl
  • 409
  • 4
  • 17
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,920
  • 2
  • 23
  • 38
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
  • 21,987
  • 6
  • 62
  • 97
Apollo
  • 1,913
  • 2
  • 19
  • 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);
EugenSunic
  • 13,162
  • 13
  • 64
  • 86