12

I have this block of code that displays the "categories" from my array into a JQuery simple list.

It works fine, but if there are 3 items from the category "basketball", the category will appear 3 times.

How could I make it so they only appear once ? Thank you.

Here's the code :

function loadCategories() {
    console.debug('About to refresh with sort type : ' + sortType);
    var items = [];

    $.each(catalog.products,
        function(index, value) {
            items.push('<li id="' + index + '">' +
                  '<a data-identity="productId"  href="./productList.page?category=' + value.category + '" >' +
                  '<p style="margin-bottom:0px;margin-top:0px;">' + value.category + '</p></a> </li>');
        }
    );

    categoryView.html(items.join(''));
    categoryView.listview('refresh');
}

Here's the code for my array :

var catalog = {"products": [
{"id": "10001",
"name": "Mountain bike",   
"color": "Grey/Black",
"long-desc": "12-speed, carbon mountain bike.",
"description": "",
"size": "20 inches",
"category": "Outdoors/ Equipment rental",
"sport": "Cycling",
"brand": "DaVinci",
"top-seller": ""},

{"id": "10002",
"name": "Pro Multi Basketball",   
"color": "Rainbow",
"long-desc": "On sale this week only! This limited edition basketball is multi-coloured, and offers pro performance. Fun and games on the court!",
"description": "Limited edition basketball.",
"size": "N/A",
"category": "Team gear",
"sport": "Basketball",
"brand": "Nike",
"top-seller": "x"},
JFFF
  • 991
  • 4
  • 17
  • 31

3 Answers3

24

I don't know how your products array is built up (so my example might need some modification according to your needs), but you could write a little piece of code that will first collect your unique categories into a new array:

var categories = [];

$.each(catalog.products, function(index, value) {
    if ($.inArray(value.category, categories) === -1) {
        categories.push(value.category);
    }
});

jsFiddle Demo

categories will hold the unique categories you need, you can use it to build your HTML from that (be careful with the IDs of those li elements though, remember that IDs cannot be duplicate, you might give them a little prefix).

kapa
  • 77,694
  • 21
  • 158
  • 175
  • Doesn't seem to work.. I'll keep you posted. I edited my question with the code from my array if you have time to look into it. Thanks again. – JFFF Jul 13 '11 at 15:16
  • @JFFF I loaded your example object into my code: [jsFiddle Demo #2](http://jsfiddle.net/3wHfB/3/). Seems to work for me. Feel free to tweak my fiddle to get the result you expect (maybe you want to add additional values into the `categories` array). – kapa Jul 13 '11 at 15:20
  • hello, is there a way to make it unique for any other field, so lets say (using the categories json) that you want all the colors without any duplicates. – Djeroen Oct 26 '15 at 20:08
  • @Djeroen Yes there is, you simply have to change the code a bit. I suggest you play with the code, understand it, then you will see it is easy. – kapa Oct 27 '15 at 08:02
4

How to get unique values by property

function groupBy(items,propertyName)
{
    var result = [];
    $.each(items, function(index, item) {
       if ($.inArray(item[propertyName], result)==-1) {
          result.push(item[propertyName]);
       }
    });
    return result;
}

Usage

var catalog = { products: [
   { category: "Food & Dining"},
   { category: "Techonology"},
   { category: "Retail & Apparel"},
   { category: "Retail & Apparel"}
]};

var categoryNames = groupBy(catalog.products, 'category');
console.log(categoryNames); 
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
1

var catalog={
    products : [
        { category: 'fos', name: 'retek' },
        { category: 'fos', name: 'item' },
        { category: 'nyedva', name: 'blabla' },
        { category: 'fos', name: 'gihi' },
    ]
};
console.log(_.uniq(_.map(catalog.products, 'category')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

Use _uniq

Parth Raval
  • 4,097
  • 3
  • 23
  • 36