I am trying to make a function as re-usable as possible.
I have a JSON file containing "products" for now.
export let productList = [
{
id: 0,
productName: "Men's Merrel Hiking Boots",
price: 65.00,
brand: "Merrell",
},
{
id: 1,
productName: "Women's Merrel Hiking Boots",
price: 65.00,
brand: "Merrell",
},
{
id: 2,
productName: "Natural Walking Stick",
price: 22.00,
brand: "Fayet",
}
]
In my case, I am trying to map through these products and return all the brands without duplicates. I know I can do that with this Set function:
function dedupeCheckboxOptions() {
return [...new Set(productList.map(product => product.brand))];
}
This works, but I am struggling to figure out a way to make this more re-usable. I would think it would look something like this so I could also use the function to maybe return the prices:
function dedupeCheckboxOptions(fullList, item) {
return [...new Set(fullList.map(product => product[item]))];
}
The syntax appears to be correct, but whenever I try to pass values, whatever iterable list I send through in the fullList parameter, it comes through undefined.
Ex:
dedupeCheckboxOptions(productList , brand)
returns undefined
Any thoughts as to why?
Top comments (1)
To make a function more reusable, it should receive the list and filter condition as an argument. This way it does not depends nor mutates values outside of its scope (pure function).
Here's an example to get unique products by brand using reduce:
The map function returns undefined if no value has been returned in an iteration, so it is not suitable for filtering.
Here's another example using reduce to get unique brands on a list:
If you're not familiar with reduce, I have an article that may help you:
dev.to/costamatheus97/ultimate-gui...