Home > Blockchain >  Why i can't remove other array element in javascript?
Why i can't remove other array element in javascript?

Time:04-19

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

CodePudding user response:

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

CodePudding user response:

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

  • Related