Removing Bought Items

Now the list remembers everything, including what you bought last week. After shopping, you'll want to clear away what's crossed off, so the app gets a button for it: Remove bought items.

The button belongs on the page, so this time you'll change index.html too, by one line. The script then finds the button with document.querySelector(), like the other elements.

How do you get rid of the bought items? With filter() from the lesson on array methods. It goes through the array and makes a new one, with only the elements for which its function returns true. Here, you want to keep the items that aren't bought:

items = items.filter((item) => !item.bought);

filter() doesn't change the old array. It returns a new one, and the code puts it into items, which is why it's good that items is a let. The list has changed, so the handler then does what the other handlers do after a change: it saves the list and shows it.

A typical mistake is to write items.filter(...) on a line of its own, without items =. The new array is made and forgotten right away, and the list stays as it was.

Instructions

In index.html, add the button under the paragraph with the amount to pay: <button id="remove">Remove bought items</button>. In script.js, find it under the other elements: const removeButton = document.querySelector("#remove");.

When removeButton is clicked, keep in items only the items that aren't bought, then save the list with saveItems() and show it with showItems(). Try it: the bread disappears, and when you run the code again, it doesn't come back.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

8/9

Next