Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda