Debug School

rakesh kumar
rakesh kumar

Posted on

How to remove remove duplicates from an array by using the Set object in react

synatax:

const uniqueArray = [...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

This creates a new array containing only the unique elements from the original array.

Why is Set Used?
JavaScript Set only stores unique values.

When you get brand names from your vehicle/admin array, many entries could repeat ("Honda", "Honda", "Yamaha"...).

Wrapping with new Set(array) removes duplicates instantly.

[...new Set(array)] converts that Set back to a normal array for sorting and React use.

If No vehicleType Selected (Show All Brands)

if (!vehicleType) {
    setFilteredBrands(
        [
            ...new Set(
                vehicalbyadmin.map((item) => item.brand?.trim() || "")
            ),
        ].sort()
    );
}
Enter fullscreen mode Exit fullscreen mode

vehicalbyadmin.map((item) => item.brand?.trim() || ""): Makes an array of all brand names, trimming whitespace, defaulting missing ones to empty string.

new Set(...): Removes duplicate brand names, so each brand appears only once.

[...new Set(...)]: Converts Set back to array (for React use).

.sort(): Sorts the brands alphabetically.

setFilteredBrands(...): Updates your state with the unique, sorted list.

c. If vehicleType Selected (Show Brands For That Type)

else {
    setFilteredBrands(
        [
            ...new Set(
                vehicalbyadmin
                    .filter((item) => item.vehicleType === vehicleType)
                    .map((item) => item.brand?.trim() || "")
            ),
        ].sort()
    );
}
Enter fullscreen mode Exit fullscreen mode

vehicalbyadmin.filter(...): Keeps only items matching your selected vehicleType.

Then map to their brand names, deduplicate with Set, make array, and sort alphabetically.

setFilteredBrands(...): Updates state with only those brands valid for the selected type.

d. Corrected Filtering Logic (Case and Field Mismatch)

const brands = [
    ...new Set(
        vehicalbyadmin
            .filter(
                (item) =>
                    (item.vehical?.toLowerCase().trim() || "") ===
                    vehicleType.toLowerCase().trim()
            )
            .map((item) => item.brand?.trim() || "")
    ),
].sort();
setFilteredBrands(brands);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)