0

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.


Sackadelic
  • 945
  • 1
  • 11
  • 21
  • What does this have to do with template literals? Do you know how to do it if you had used plain string concatenation? – Bergi Feb 15 '22 at 12:55
  • 1
    "*I'm getting separate lists of categories*" - please post the code that produces multiple lists. In the code snippet you've shown so far, only a single list (weirdly, inside a `
  • ` not an `
      `) is generated.
  • – Bergi Feb 15 '22 at 12:56
  • Edited to show full expression. – Sackadelic Feb 15 '22 at 13:03
  • 1
    Use `results.products.flatMap(item => item.productCategories.split(', '))`. Then [deduplicate](https://stackoverflow.com/q/1960473/1048572) that and then put it into your template. – Bergi Feb 15 '22 at 13:11
  • I just updated my code again, If you could offer some assistance, I'd appreciate it, I'm stuck on this one. Thanks, Bergi. – Sackadelic Feb 15 '22 at 13:57
  • `flatMap` returns the array that you need to pass into the `new Set`, do not `map()` there. Maybe try not do put everything in a single expression but use some helper variables, and do some debugging on the temporary values – Bergi Feb 15 '22 at 16:05