Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
splice() Method does not remove a specific element from My Array

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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar

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)
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda