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

251
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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