Find indexes of multiple minimum value in an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of numbers like this −

const arr = [1,2,3,4,1,7,8,9,1];

Suppose we want to find the index of the smallest element in the array i.e. 1 above.

For this, we can simply use −

const min = Math.min.apply(Math, arr);
const ind = arr.indexOf(min);

The above code will successfully set ind to 0, which indeed is correct.

But what we want to achieve is that if there are more than one minimum elements in the array, like in the above array (three 1s), then we should return an array containing all the indices of minimum elements.

So, for this array, our desired output is the following i.e. three 1s found at index 0, 4, and 8 −

const ind = [0, 4, 8]

We are required to write a JavaScript function that takes in an array of numbers and returns an array of all the indices of minimum elements in the array.

Example

Following is the code −

const arr = [1,2,3,4,1,7,8,9,1];
const minArray = arr => {
   const min = arr.reduce((acc, val) => Math.min(acc, val), Infinity);
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr[i] !== min){
         continue;
      };
      res.push(i);
   };
   return res;
};
console.log(minArray(arr));

Output

This will produce the following output in console −

[ 0, 4, 8 ]
raja
Published on 18-Sep-2020 17:05:48
Advertisements