Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Category 1 (5)
  • Category 2 (3)
  • Category 3 (1)

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?

like image 293
mmmoustache Avatar asked Mar 09 '13 19:03

mmmoustache


3 Answers

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] + ')');
}
like image 113
Mr.Pohoda Avatar answered Nov 17 '22 06:11

Mr.Pohoda


$(function() {
    var categories = {};
    $(".categories li").each(function() {
        var category = $(this).data("category");

        if (categories.hasOwnProperty(category) === false) {
            categories[category] = 1;
        } else {
            categories[category]++;
        }
    });

    console.log(categories);
})

Example

like image 4
Andreas Avatar answered Nov 17 '22 06:11

Andreas


May be dirty, but it's what I came up with:

var iterate = 1;
$('ul.categories li').each(function (i, v) {
    var thisCat = $(v).data('category');
    if ($('div#' + thisCat).length > 0) {
        $('div#' + thisCat).text(thisCat + ' (' + ++iterate + ')');
    } else {
        iterate = 1;
        var newDiv = '<div id="' + thisCat + '">' + thisCat + ' (1)</div>';
        $('#result').append(newDiv);
    }
});

And, fiddle.

like image 2
hjpotter92 Avatar answered Nov 17 '22 04:11

hjpotter92