-1

We have an array of numbers like this:

const array = [2, 1, 3, 1];

the minimum number in the array is 1 right? Now I want to return a new array containing the index or indices of the minimum numbers in the given array. So in above array the desired result would be:

[1, 3] // indices of minimum number which is 1

If there is only one element in the array we should return 0 right...

Sara Ree
  • 3,417
  • 12
  • 48
  • Please include your code that attempts to implement this and explain how it's failing so someone can help you. – jarmod Jan 24 '21 at 20:03
  • There are many good solutions here with explanations: [Smallest number in array and its position](https://stackoverflow.com/questions/15455247/smallest-number-in-array-and-its-position) – Zac Anger Jan 24 '21 at 20:07

4 Answers4

1

You could use indexOf and a while loop:

const array = [2, 1, 3, 1];
const minElement = Math.min(...array);
const minElementIndexes = [];
let indexOfMinElement = array.indexOf(minElement);
while (indexOfMinElement != -1) {
    minElementIndexes.push(indexOfMinElement);
    indexOfMinElement = array.indexOf(minElement, indexOfMinElement + 1);
}
console.log(minElementIndexes);
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

Step by step:

  1. Determine the minimum number.
  2. Map the array so that the minimum numbers are replaced with the indexes, and other numbers are replaced with undefineds.
  3. Filter out the undefineds.

const array = [2, 1, 3, 1]
const min = Math.min(...array) // 1
const result = array
  .map((number, index) => number === min ? index : undefined) // 2
  .filter((item) => item !== undefined) // 3
console.log(result)
Matias Kinnunen
  • 7,828
  • 3
  • 35
  • 46
1

Get the min number, then iterates through the array by his index:

const array = [2, 1, 3, 1];

let reduced = array.reduce((x, y) => x < y ? x : y);
console.log(reduced)
let result = [];

for(let i in array){
    if(array[i] == reduced){
        result.push(i)
    }
}
console.log(result)
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

you can use one loop where you keep tracking minValue:

const array = [2, 1, 3, 1];

let minValue = array[0]; 

const indexes = array.reduce((arr, val, idx) => {
  if (idx === 0) return [idx];
  if (val > minValue) return arr;
  if (val === minValue) {
    arr.push(idx);
    return arr;
  };
  minValue = val;
  return [idx];
}, []);

console.log(indexes)
buzatto
  • 9,704
  • 5
  • 24
  • 33