Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splice on forEach loop not working properly

Tags:

javascript

I have the following context:

https://jsfiddle.net/eqntaqbt/2/

obj.forEach(function(user, index){
    var userName = user.name;
    console.log(index, userName);

  if(index === 5 || index === 2){
    obj.splice(index, 1);
  }
});

I am using a forEach loop and splice to remove the item in position 5 and 2 on the obj array. But for some reason its not working properly.

What am I doing wrong?

like image 294
gespinha Avatar asked Mar 13 '23 17:03

gespinha


1 Answers

Your code is splicing while looping. Spliced elements are accessed even they are no more existing. That leads to undefined elements.

You may consider Array#filter

var obj = [{ "index": 0, "name": "Odonnell Noble", "gender": "male", "company": "DIGIQUE", "eail": "[email protected]" }, { "index": 1, "name": "Marie Oneal", "gender": "female", "company": "CANOPOLY", "email": "[email protected]" }, { "index": 2, "name": "Adrienne Marsh", "gender": "female", "company": "XOGGLE", "email": "[email protected]" }, { "index": 3, "name": "Goff Mullins", "gender": "male", "company": "ENDIPIN", "email": "[email protected]" }, { "index": 4, "name": "Lucile Finley", "gender": "female", "company": "AQUASSEUR", "email": "[email protected]" }, { "index": 5, "name": "Pitts Mcpherson", "gender": "male", "company": "QUARX", "email": "[email protected]" }];

obj = obj.filter(function (user, index) {
    return (user.index !== 5 && user.index !== 2);
});

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
like image 105
Nina Scholz Avatar answered Mar 15 '23 05:03

Nina Scholz