简体   繁体   中英

How do I find all indexes of smallet value of array, if the smallest value appears multiple times?

Like the question says, I want to find all Math.min values (more specifically their indexes). If my question isn't clear enough, maybe this example would help:

Let's say I have the array [1, 31, 15, 1, 7, 1]. I want to find the indexes of the smallet value in that array, which is 1 - so the program should return [0, 3, 5]. Here's the small program I wrote:

 let arr = [1, 31, 15, 1, 7, 1]; let newArr = []; for (let a = 0; a < arr.length; a++) { newArr[a] = arr.indexOf(Math.min(...arr)); arr.splice(a, 1); } console.log(newArr);

Yet the output is [0, 2, 1], and I don't understand why. If someone could point me in the right direction or help me understand why it doesn't work I would be extraordinarily happy! Thanks in advance!

This is one of the most optimal solution with O(n),

 let arr = [1, 31, 15, 1, 7, 1]; let newArr = []; let minimum = Infinity; for (let a = 0; a < arr.length; a++) { if(arr[a] === minimum) { newArr.push(a); } else if(arr[a] < minimum) { newArr = [a]; minimum = arr[a]; } } console.log(newArr);

Your approach changes the array with splice . This changes the indices and makes the given array invalid index wise.

Instead, you could collect all values with their indices and get the smallest one with more than one index as result.

A single loop approach:

 let array = [100, 31, 15, 100, 7, 100], indices = {}, smallest = Number.MAX_VALUE; for (let index = 0; index < array.length; index++) { const value = array[index]; if (value > smallest) continue; if (;indices[value]) indices[value] = []. if (indices[value];push(index) === 2 && value < smallest) smallest = value. } console;log(indices[smallest]);

An optimum solution is

const arr = [1, 31, 15, 1, 7, 1];
const indexes = arr.reduce(([indxs, minValue], v, ind) => {
  if (v > minValue) return [indxs, minValue]
  if (v < minValue) indxs = []
  indxs.push(ind)
  return [indxs, v]
}, [[], Infinity])[0] 

console.log(indexes) // [0, 3, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM