Skip to content Skip to sidebar Skip to footer

Total Data Attribute Values By Category

I'm trying to find the total amount group by data attribute name from a list using jQuery. Similar to grouping categories and find the sum. For example, I would like to create some

Solution 1:

Using pure JavaScript:

Example Here

functiongetCategoryTotal(cat) {
    var total = 0,
        elements = document.querySelectorAll('[data-category="' + cat + '"]');

    Array.prototype.forEach.call(elements, function (el, i) {
        total += parseInt(el.dataset.amount, 10);
    });

    return total;
}

console.log(getCategoryTotal('group1')); // 3console.log(getCategoryTotal('group2')); // 5console.log(getCategoryTotal('group3')); // 3

Solution 2:

I guess you asked about a jQuery way of doing so, which I did:

$.fn.amountByData = function(dataAttr, amountDataAttr) {
    if (typeof amountDataAttr == "undefined")
        amountDataAttr = "amount";

    var dataAmountArr = newArray();

    $(this).each(function() {
        var dataAttrVal = $(this).data(dataAttr);

        if (typeof dataAmountArr[dataAttrVal] == "undefined")
            dataAmountArr[dataAttrVal] = parseInt($(this).data(amountDataAttr));
        else 
            dataAmountArr[dataAttrVal] += parseInt($(this).data(amountDataAttr));
    });

    return dataAmountArr;
};

Here's how I would achieve it jQuery way ! This gives a LOT of flexibility, because you can choose by which data attribute you want to calculate the amount based on, and you can also choose to precise a different amount data attribute if it is not named amount.

PS: I know an answer has already been chosen, but contrary to @Josh Crozier, I understood you wanted a jQuery method to achieve your goal.

Cheers,

Post a Comment for "Total Data Attribute Values By Category"