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

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

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 Denunciar

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 Denunciar

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