synatax
:
const uniqueArray = [...new Set(array)];
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()
);
}
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()
);
}
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);
Top comments (0)