1

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

  • because you are modifying the array while still looping through it using the original indexes. The map loop will be at index `1` when meeting the number `2` but the array at that point will already be modified and at that position will corrispond the element `3` – Diego D Aug 03 '22 at 07:42

4 Answers4

1

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

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);
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
0

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)
Abhay Srivastav
  • 754
  • 6
  • 16
0

You want to filter the array

let mix = [1, 2, 3, "E", 4, "l", "z", "e", "r", 5, "o"];

let newMix = mix.filter(function (ele, index) {
    return (typeof ele !== "number") 
  
    
})

console.log(newMix);
IT goldman
  • 14,885
  • 2
  • 14
  • 28