-1

I have a JSON array and an array of IDs that needs to be deleted from the JSON array. I have tried to do with iteration but there is always something left in the JSON array.

Controller:

    console.log('before delete' .....);
    console.log('idsToBeDeleted:'......);
        for(var i=0; i<inputs.length;i++){
            for(j=0; j<idsToBeDeleted.length;j++){
                if(inputs[i].x== idsToBeDeleted[j]){
                    //console.log('inputs[i] '+ inputs[i]);
                    console.log('deleting '+inputs[i].w+ ' ' + inputs[i].x+' '+inputs[i].y+' '+inputs[i].z)
                    inputs.splice(i, 1);        
    
                    //delete inputs[j]; 
                }
            }
        }
console.log('after delete:'.....)
   

Console Output:

                      w                   x            y    z
before delete: a4y11000001fbIHAAY a5011000000LTHGAA4 100000 1
before delete: a4y11000001fbIMAAY a5011000000LTHGAA4 100000 3
before delete: a4y11000001fbIHAAY a5011000000LTHHAA4 25000 2
before delete: a4y11000001fbIMAAY a5011000000LTHHAA4 25000 4

idsToBeDeleted: a5011000000LTHGAA4

deleting:      a4y11000001fbIHAAY a5011000000LTHGAA4 100000 1

after delete:  a4y11000001fbIMAAY a5011000000LTHGAA4 100000 3
after delete:  a4y11000001fbIHAAY a5011000000LTHHAA4 25000 2
after delete:  a4y11000001fbIMAAY a5011000000LTHHAA4 25000 4
     

From the above code and output, you can see I am trying to delete by x column after matching with idsToBeDeleted. But in the above scenario below record is being left out. I am not sure what I am doing wrong.

after delete:  a4y11000001fbIMAAY a5011000000LTHGAA4 100000 3
2
  • You should edit to add more of your code. It looks like you left some parts out and those parts could be important. May 12 at 17:31
  • Yes, I did leave but those parts are irrelevant, but from the console log before and after you can understand that issue lies remain in this particular part. Rest assured there is no other code between before delete and after delete console log.
    – Akash
    May 12 at 17:49
0

The problem is that you're trying to delete an item from an array in place. When i = 0, i is the item where w = 'a4y11000001fbIHAAY. However, when you remove that item from the list, everything slides down. The item at i[0] is now the item where w = 'a4y11000001fbIHAAY'. When i increments to 1, it skips over this item entirely, thus it doesn't get deleted. Using filter here should work:

inputs = inputs.filter((i) => (idsToBeDeleted.indexOf(i) === -1));
2
  • 2
    Array.prototype.contains is a bit easier to read, though: inputs.filter(i => !idsToBeDeleted.contains(i))
    – sfdcfox
    May 12 at 19:36
  • aha! Understood. Thanks your code is working fine. need to learn es6 js skills. any good source you recommend?
    – Akash
    May 13 at 4:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.