I Have This Code:
let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];
let newMix = mix.map(function (ele, index) {
if (typeof ele === "number") {
mix.splice(index, 1)
}
})
console.log(mix);
And The Output Is As Follows:
[2, 'l', 'z', 'e', 'r', 'o']
My Question Is: Why Didn't splice() Delete Element 2
As you splice, the indices are changing. I believe the collection operation you want here is filter rather than map:
let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];
mix = mix.filter(x => typeof x != "number");
console.log(mix);
It's not a good idea to alter the array during a map/forEach, because when you delete an element at index 0, the element at index 1 becomes index 0, and the element at index 2 comes to index 1. So in your case, 1 at index 0 is removed, 2 moves to index 0, and the next iteration starts at index 1 which has 3 currently. So 3 is removed.
See ECMAScript standard specification for
Array.prototype.map to get a better idea.
A better way to do this would be using filter, here's an approach
let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];
let newMix = mix.filter(isNaN);
// OR you can use typeof: let newMix = mix.filter((element) => typeof element !== "number");
console.log(newMix);
Because, when you are splicing the mix array the indexes are being modified as a result.
You can use filter instead
let newMix = mix.filter(function(elem){
return typeof elem !== "number"
})
console.log(newMix)