
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find indexes of multiple minimum value in an array in JavaScript
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 ]
- Related Questions & Answers
- How to find the minimum value of an array in JavaScript?
- Return indexes of greatest values in an array in JavaScript
- Find the closest value of an array in JavaScript
- Function that returns the minimum and maximum value of an array in JavaScript
- Find minimum adjustment cost of an array in C++
- Find minimum adjustment cost of an array in Python
- How to find the maximum value of an array in JavaScript?
- Find the maximum possible value of the minimum value of modified array in C++
- Smallest Common Multiple of an array of numbers in JavaScript
- Find value in a MongoDB Array with multiple criteria?
- Sort an array of objects by multiple properties in JavaScript
- Find and return array positions of multiple values JavaScript
- Finding minimum time difference in an array in JavaScript
- Find frequency of smallest value in an array in C++
- Minimum value among AND of elements of every subset of an array in C++