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

108
Visualizações
Why i can't remove other array element in javascript?

I am working with arrays now but if I remove the second element that I choose the first one that I removed keeps returning to its spot. How can I solve this?

Here is the Code:

const fruits = ['Apple', 'Banana','Lemon', 'Guava'];

const removeItem = (arr, item) => {
    let newArray = [...arr];
    const index = newArray.findIndex((element)=>element===item)
    if(index !== -1){
        newArray.splice(index, 1)
        return newArray
    }
}

console.log(removeItem(fruits, 'Guava'))

console.log(removeItem(fruits, 'Lemon'))

Output:

(3) ['Apple', 'Banana', 'Lemon'] //I removed Guava
(3) ['Apple', 'Banana', 'Guava'] //I removed Lemon
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your original array is a const and cannot be updated. So it is using all original values. Here is a working version that removes from the original array.

let fruits = ['Apple', 'Banana','Lemon', 'Guava'];

const removeItem = (arr, item) => {
    let newArray = [...arr];
    const index = newArray.findIndex((element)=>element===item)
    if(index !== -1){
        newArray.splice(index, 1)
        fruits = newArray;
        return newArray
    }
    
}

console.log(removeItem(fruits, 'Guava'))

console.log(removeItem(fruits, 'Lemon'))

about 4 years ago · Juan Pablo Isaza Relatório

0

Keywords to think about: pop push remove index placeholder I don't understand what you are trying to achieve. Well, I never tried Guava.

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