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

250
Views
Javascript splice removes wrong element

I am somewhat bamboozled over this very simply code not working correcly:

 //find the index to be removed
 cardData.likeData.likeUids.forEach ((entry, index) => {
    if (entry === uid){
      uidFound = true
      uidIndex = index
      console.log ("Found uid, index is " + uidIndex)
      //console shows correct index
    }
  })
  let newLikeUids = cardData.likeData.likeUids.splice (uidIndex, 1)
  //instead of deleting the found index, the element before the index is removed... for some reason

Any idea why this is not working?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I have noticed the problem is you probably using the splice in the wrong way.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice()

But in your code, you are trying to assign the value of splice to a value which will not working.

You probably mix the slice and splice. I think in this situation, you should use slice instead.

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

about 4 years ago · Juan Pablo Isaza Report

0

You should use findIndex. I don't know how your array looks like but in a similar case where you want to remove the first 1 from an array of 1 and 0, you'd write something like this:

const arr = [0,0,0,0,0,1,0,0,0];
arr.splice(arr.findIndex(e => e === 1), 1);
console.log(arr);

about 4 years ago · Juan Pablo Isaza Report

0

Maybe filter method of Array can help you

cardData.likeData.likeUids.filter ((entry) => {
    return entry !== uid;
});

If you have many uids to remove

you could try

cardData.likeData.likeUids.filter ((entry) => {
    return uids.indexOf(entry) === -1;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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!