jqueryhtmljquery-data

Group and count HTML elements by data attribute in jQuery


I'm trying to group each instance of a data attribute into a list from the number of occurrences of each attribute in a page, using jQuery. Similar to grouping categories or tags in a news section.

For example, I would like to create something like this:

from this html:

<ul class="categories">
   <li data-category="category-1">Category 1</li>
   <li data-category="category-1">Category 1</li>
   <li data-category="category-1">Category 1</li>
   <li data-category="category-1">Category 1</li>
   <li data-category="category-1">Category 1</li>
   <li data-category="category-2">Category 2</li>
   <li data-category="category-2">Category 2</li>
   <li data-category="category-2">Category 2</li>
   <li data-category="category-3">Category 3</li>
</ul>

How can I achieve this in jQuery? Is it even possible?


Solution

  • It is possible, check this jsFiddle I've created.

    var categories = {},
        category;
    
    $('.categories li[data-category]').each(function(i, el){
        category = $(el).data('category');
        if (categories.hasOwnProperty(category)) {
            categories[category] += 1;
        }
        else {
            categories[category] = 1;
        }
    });
    
    // print results
    for(var key in categories){
        console.log(key + ' (' + categories[key] + ')');
    }