I have the following code:
// function loadProducts
const products = [
{ name: 'koffie', price: 2.50, group: 'warme dranken' },
{ name: 'thee', price: 2.50, group: 'warme dranken' },
{ name: 'cola', price: 3.50, group: 'koude dranken' },
{ name: 'ice tea', price: 3.50, group: 'koude dranken' },
{ name: 'patat', price: 3.50, group: 'friet' },
{ name: 'patat mayo', price: 3.50, group: 'friet' },
{ name: 'frikandel', price: 3.50, group: 'snacks' },
{ name: 'kroket', price: 3.50, group: 'snacks' }
]
const list = document.querySelector('#productList');
const addProducts = (array, element) => {
array.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name;
element.appendChild(li);
});
}
addProducts(products, list);
<div id='productList'></div>
This code generates a list of products in HTML. Now I want to filter with buttons on the front end and filter on the group string. I know that I have to use filter method but I am stuck on this.
document.getElementById('warme-dranken').addEventListener('click', function() {
});
2
Answers
There are a lot of ways of doing this. Here’s my take on it.
When creating the
li
‘s, add thedata-group
to itAfter creating the
li
‘s, create and calladdGroupBoxes
that willGet all the unique groups
How to get distinct values from an array of objects in JavaScript?
Create a
<input type='checkbox'>
and a<label>
for that group, setchecked
totrue
to make the checkboxes ‘hide’ the items when pressed.Add a
onchange
functionIn the
onchange
, I’ve called itonCheckboxToggle
, we candata-group
matches the event value.hide
class that will applydisplay: none
to hide itIf you want the checkboxes to work the other way around, you can change the class or add the class to each item in
addProducts
You seams to have the base figured out, which is great.
Now, for the filter part, we are missing a bit of information so it’s hard to produce a complete answer. For example, you want to filter by what property ?
In any case, you will want to use a
if
to filter out any product that does not match your filter. This if could be in theforEach
function you are already using.With that in mind, you could add a parameter to your
addProducts
function which would contains what we call a "predicate". It’s a function that will be called for each product and used to determine if we want to show it or not.Simply put, it would look something like that:
this add the ability to filter the product list if needed. You can use this new ability and call the function with a new predicate parameter, in the click listener of your button:
This will add, to the list, only the item of the group
warme draken
.There is a problem, however. Since the list already contain some items, some of them are duplicated. To fix that, we could empty the list first, and then only add the items that match the predicate:
here is a working example