Search code examples
javascriptarrayssplicearray-splice

Splicing first object returns TypeError: Cannot read property of undefined


I have an array like this:

var arrSession = [ { name: 'Product 01', groupID: '50303', delivery: 'mail'}, { name: 'Product 02', groupID: '50403', delivery: 'bike'} ]

And this Loop to delete specific objects:

for(var i=0, len=arrSession.length; i<len; i++) {
    if (arrSession[i].groupID == getGroupID && arrSession[i].delivery == getDelivery) {
        arrSession.splice(i, 1);
    }
}

If I'm deleting the last object, all works fine:

var getGroupID = 50403;
var getDelivery = bike;

But if I'm deleting the first object:

var getGroupID = 50303;
var getDelivery = mail;

I get an error:

TypeError: Cannot read property 'groupID' of undefined  

Why so and how to solve it?

Edit:

If there is only one object all is fine too.

var arrSession = [ { name: 'Product 01', groupID: '50303', delivery: 'mail'} ]

Solution

  • Short Answer: Due to the for loop syntax. Initialization happens only once. You missed to update len after splicing.

    for ([initialExpression]; [condition]; [incrementExpression]) statement

    Solution: As already mentioned in the other answers, you can break the loop (which will work if you are spicing only one item).

    const arrSessionActual = [{
      name: 'Product 01',
      groupID: '50303',
      delivery: 'mail'
    }, {
      name: 'Product 02',
      groupID: '50403',
      delivery: 'bike'
    }];
    
    function removeItem(arrSession, getGroupID, getDelivery) {
      for (var i = 0,
          len = arrSession.length; i < len; i++) {
        if (arrSession[i].groupID == getGroupID && arrSession[i].delivery == getDelivery) {
          arrSession.splice(i, 1);
          len = arrSession.length; // This is missing
        }
      }
    
      console.log(arrSession);
    }
    
    removeItem(arrSessionActual.slice(), 50403, 'bike');
    removeItem(arrSessionActual.slice(), 50303, 'mail');