0

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.

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I see, so there is no way to delete trough a loop?
could use the splice function to change your array, but why do you need to delete this array and not create a new one?
1

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);

Comments

-1

You must decrement the index variable after splice like this :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.