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

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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