How to Splice method performance error with max

Viewed 48

I have a dilemma with this line of code

let numero = [11,5,7,9,10,12];
console.log(numero.splice(Math.min.aply(null, numero), 1));
console.log(numero);

This line of code should eliminate the number 5 which is the smallest of the array, but it eliminates the 12, I have tried in different ways, but I can't get it to eliminate the 5. I have not found the error thank you all.

2 Answers

You found the number, but then you have tried to remove it by itsef instead of by its index, which is what splice was expecting. Try this:

numero.splice(numero.indexOf(Math.min(...numero)),1)

Math.min will return the minimum in your array but splice would like to have the position of the min value inside your array. You need to look for the index(position) and not for the value itself.
You can use the .indexOf() method

Note: Prefer the use of the spread operator ... to call variadic functions.

Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose new with apply.

// bad
const x = [1, 2, 3, 4, 5];
console.log.apply(console, x);

// good
const x = [1, 2, 3, 4, 5];
console.log(...x);

// bad
new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));

// good
new Date(...[2016, 8, 5]);

In this repository you can read more about best practices

let numero = [11, 5, 7, 9, 10, 12];

console.log(numero.splice(numero.indexOf(Math.min(...numero)),1));

Related