Question

When i try to delete some object from columnListA with the objects present in columnListB i'm getting Error: columnListA[i] is undefined

can anyone please tell me some solution for this.

my json list is shown below:

columnListA =[ {id:"a1", value:"XYZ"},{id:"a2", value:"ABC"},{id:"a3", value:"JHI"},{id:"a4", value:"PLM"}]

columnListB =[ {id:"a1", value:"XYZ"}]

My code is this

for ( var j = 0, selLength = columnListB.length; j < selLength; j++)
{
    for ( var i = 0, nonSelLength = columnListA.length; i < nonSelLength; i++)
    {
     if (columnListA[i].id=== columnListB[j].id)
     {
       columnListA.splice(i, 1);
     }
    }
}
Was it helpful?

Solution 2

Try:

for ( var j = 0; j < columnListB.length; j++)
{
    for ( var i = 0; i < columnListA.length; i++)
    {
        if (columnListA[i].id === columnListB[j].id)
        {
            columnListA.splice(i, 1);
        }
    }
}

JSFiddle

Remove nonSelLength = columnListA.length; i < nonSelLength; from loops and just define variable as less than length of the object

OTHER TIPS

You're getting this because you're changing columnListA inplace. Since you delete an element, its length passes from 4 to 3, but you still iterate until i = 3.

I suggest creating a new array, instead of changing it inplace and risking this type of error. Example:

columnListA = columnListA.filter(function(nonSel) {
  return columnListB.some(function(sel) {
    return sel.id !== nonSel.id;
  });
});

Array#filter takes a function, and returns a new array that contains only the elements for which the function returns true.

Array#some takes a function, and returns true if the function returns true for all the elements on the array, and false otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top