0

I cannot seem to remember how to do this, although it should be quite simple. I am displaying the categories in a select dropdown so that a customer can filter which products on my website, and I don't want it to show duplicate categories, since multiple products are in the same categories.

<select name="category" id="cateogry">

            <% if(data.length){ 
              for(var i = 0;i < data.length;i++) { %>
            <option value="<%=data[i].CATEGORY%>"><%=data[i].CATEGORY%></option>
            <% }
        }else{ %>
         <p>DOESN'T WORK</p>
      <% } %>
          </select>

what is the best way to go about this. Thanks in advance

Gianluca
  • 900
  • 8
  • 27

3 Answers3

0

create array with category names. then create Set and then again create array from set.

[...(new Set(data.map(item => item.CATEGORY)))].forEach(category => {
   <option..............>
})
Robert
  • 2,538
  • 1
  • 9
  • 17
0

As described in detail in a previous question here Remove duplicate values from JS array

I would prefer this ES6 solution

function uniq(a) {
   return Array.from(new Set(a));
}

Also, as far as I know, iterating an array with For loop is not a very optimised solution

Ozgur Sar
  • 2,067
  • 2
  • 11
  • 23
  • I am actually making a call from a database (db2), and then passing the info to the front end. is it still best to do what you mentioned? – Gianluca Oct 26 '20 at 20:34
  • @Gianluca using Set data structure is best approach. – Robert Oct 26 '20 at 20:40
  • @Gianluca, if it won't break any other sections of the web site, I would prefer to do it at the backend. But it is just a prersonal preference where you actually sort & remove the duplicates. – Ozgur Sar Oct 27 '20 at 17:32
0

unique is result

let data_categories= data.map(item=>item.CATEGORY);
let unique = data_categories.filter(function(elem, index, self) {
  return index === self.indexOf(elem);
});
// unique is result