Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!