I am returning product categories based on search results, and I want to list all product categories as one single list with duplicates filtered out. Currently, I'm returning something like:
item.productCategories
which returns a string of URLS, like so:
"<a href=\"https://test.local/product-category/guitar-pickups/\" rel=\"tag\">Guitar Pickups</a>, <a href=\"https://test.local/product-category/hum-cancelling/\" rel=\"tag\">Hum-Cancelling Pickups</a>
I'm then splitting them using .split(",")
and the following expression below to list them in a template literal:
`<ul> ${results["products"].map((item) => `
<li class="search-result">${item.productCategories
.split(",")
.map((category) => `<li>${category}</li>`)
.join("")}
</li>`)}
</ul>`
Result:
I'm getting separate lists of categories like so:
List 1:
- Category 1
- Category 3
- Category 2
List 2:
- Category 1
- Category 2
I'd like to flatten all of these arrays, combine them into one array and then filter out duplicates and return a single array. I do not know where to start with doing this in a Template Literal. Any ideas?
Update:
Thanks to @Bergi I am now able to reduce all links into a new array, but I'm stuck deduplicating the array.
Updated Code:
<ul>${results.products.flatMap((item) => item.productCategories.split(", "))}</ul>
I tried <ul>${results.products.flatMap((item) => item.productCategories.split(", ")).map((cat) => console.log([...new Set(cat)]))}</ul>
but that blows the individual strings within the array into sub arrays
I'm sorry, I'm new at Array methods. Any help is appreciated.
`) is generated.