DEV Community

mitchelln11
mitchelln11

Posted on

How to Make a Reusable Function that Removes Duplicates

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",
    }
]
Enter fullscreen mode Exit fullscreen mode

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))];
}
Enter fullscreen mode Exit fullscreen mode

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]))];
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Any thoughts as to why?

Top comments (1)

Collapse
 
costamatheus97 profile image
Matheus Costa • Edited

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:

const getUniqueProductsByBrand = (products, brand) => {
    return products.reduce((allProducts, currentProduct) => {
        if(currentProduct.brand === brand && !allProducts[currentProduct.id]) {
            allProducts[currentProduct.id] = currentProduct
        }

        return allProducts
    }, {})
}
Enter fullscreen mode Exit fullscreen mode

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:

getUniqueBrands = (products) => {
    return products.reduce((allBrands, currentProduct) => {
        if(!allBrands.includes(currentProduct.brand)) {
            allBrands.push(currentProduct.brand)
        }

        return allBrands
    }, [])
}
Enter fullscreen mode Exit fullscreen mode

If you're not familiar with reduce, I have an article that may help you:

dev.to/costamatheus97/ultimate-gui...