Home > Software engineering >  Loop on array and delete objects with specific value
Loop on array and delete objects with specific value

Time:12-04

I have an array similar than this one, called websiteproducts:

[{
        "memberid": 280,
        "state": "AL",
        "product": "1",
        "deleteProduct": 1,
        "waitingDays": 0
    },
    {
        "memberid": 280,
        "state": "AL",
        "product": "2",
        "deleteProduct": 1,
        "waitingDays": 0
    },
    {
        "memberid": 280,
        "state": "AL",
        "product": "3",
        "deleteProduct": 1,
        "waitingDays": 0
    },
    {
        "memberid": 280,
        "state": "AL",
        "product": "4",
        "deleteProduct": 0,
        "waitingDays": 0
    }

]

And Im trying to delete all objects that have "deleteProduct" = 1 as follows:

 for (let i = 0; i < websiteproducts.length; i  ) {
                if (websiteproducts[i].deleteProduct == 1) {
                    websiteproducts.splice(i, 1)
                }
            }

But only the first object is deleted.

I believe it has to do with the fact that Im deleting the item from the array on the fly.

But this one works, when copying the objects to a new array:

let finalProducts = []
            for (let i = 0; i < websiteproducts.length; i  ) {
                if (websiteproducts[i].deleteProduct != 1) {
                    finalProducts.push(websiteproducts[i])
                }
            }

Is there a way to delete the objects straight from the array through a loop, without having to create a second array?

Thanks.

CodePudding user response:

You can use the filter function on the array, it only returns the elements that meet the condition.

let finalProd = websiteproducts.filter(prod => prod.deleteProduct != 1)

CodePudding user response:

You don't have to use a loop at all. You can use Array.prototype.filter().

This returns a new array with the filtered elements removed:

const filtered = websiteproducts.filter(product => product.deleteProduct != 1);

CodePudding user response:

You must decrement the index variable after splice like this :

websiteproducts.splice(i, 1); i--;

  • Related