Return an array of all the indices of minimum elements in the 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. For this we can simply use −

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

This 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 (3 ones), then we should return an array containing all the indices of minimum elements.

So, for this array, our desired output is −

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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[ 0, 4, 8 ]
raja
Published on 21-Oct-2020 15:38:46
Advertisements