1

I am trying to get the indexes of the 5 smallest values in an array.

I've tried the code below, however it gives the error: Math.min.apply(...).indexOf is not a function. I'm just not sure what I can use as an alternative?

var smallest = [];
for (var i = 0, length = distances.length; i < length; i++) {
    var min = Math.min.apply(null,distances).indexOf();
    if (smallest.length <= 5) {
        smallest.push(min);
    }
    console.log(smallest);
}

Thanks!

3
  • 1
    Well that expression does not make sense; Math.min() returns a single numeric value. Commented Jul 10, 2019 at 12:18
  • 2
    Object.entries(distances).sort(([i,a],[j,b]) => a - b).map(([index]) => index).slice(0, 5) Commented Jul 10, 2019 at 12:22
  • 1
    What if the same (small) value is in the array twice? Which index do you want? Commented Jul 10, 2019 at 12:22

3 Answers 3

5

You could get the keys, sort them with the values and take the top five.

var indices = [...distances.keys()]
        .sort((a, b) => distances[a] - distances[b])
        .slice(0, 5);
Sign up to request clarification or add additional context in comments.

2 Comments

keys returns an iterator.
@charlietfl take a look at mdn
3

You can use Object.entries() to get [index, value] pairs that you can now sort by value to get the order.

const distances = [1, 4, 8, 3, 3, 5, 9, 0, 4, 2];
const indices = Object.entries(distances)
                      .sort(([,a],[,b]) => a - b)
                      .map(([index]) => +index)
                      .slice(0, 5)
console.log(indices);

Nina's version is better :)

3 Comments

There's no need to declare i or j here, you can just write [,a] and [,b] :)
@Kobe thx, wasn't sure. And didn't want to use _ and __ for these unused arguments
Yeah, destructuring can get weird sometimes :P
0

You could add an index to each element, sort the data in ascending order, then splice the first 5 values:

const data = [1, 4, 8, 3, 3, 5, 9, 0, 4, 2]

const indices = data.map((e,i) => [e, i])
  .sort()
  .splice(0,5)
  .map(([,el]) => el)

console.log(indices)

4 Comments

How would this return the indexes?
Ah, yes, ill fix that now @charlietfl
@T.J.Crowder haha yes, I always fall victim to not writing in strict mode when writing answers here too.
data.slice().map(...) is pointless. map already creates a new Array, you don't need slice() anymore. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.