Search code examples
javascriptarraysloopssumparseint

Calculate the sum of arrays with a dynamic name in Javascript


I'm trying to calculate the sum of arrays with a dynamic name in Javascript. Here's an example of my code:

            var sum = [];
            var totalPrice = 0;
            //For each unique category
            for (var i = 0; i < uniqueCategoryNames.length; i++) {
                //Create a new array for each unique category
                sum[i] = new Array();

                //Loop through each item with the class name of the unique category
                $('.' + uniqueCategoryNames[i]).each(function () {

                    //Push the trimmed price in the array that matches the category
                    sum[i].push(Number($(this).text().replace('€', '').replace(' ', '').replace(',','.')));
                });

                for (var x = 0; x < sum[i].length; x++){
                    totalPrice += sum[i][x];

                }
                console.log(totalPrice);

            }

To sketch an image of my situation: I have a shopping cart in which there are various items within 2 different categories. I want to know what the subtotal of each item of a specific category is.

So imagine I've got 2 items that are both $5 in a category called tops and 3 items that are all $12 in a category called pants. In this case the sum needs to calculate that I have a total of $10 in my tops category and a total of $36 in my pants category.

I'm stuck on the part where I calculate the sum on all of my arrays. I'm trying to do that here:

for (var x = 0; x < sum[i].length; x++){
     totalPrice += sum[i][x];

}

How do I calculate the sum over each one of my dynamically created arrays?


Solution

  • How about this :

    let totalPrice = 0;
    let subTotals = {};
    //For each unique category
    for (let i = 0; i < uniqueCategoryNames.length; i++) {
    
      let subTotalCurrentCategory = 0;
      //Loop through each item with the class name of the unique category
      $('.' + uniqueCategoryNames[i]).each(function() {
    
        //Add the current price to the subTotal
        let currentPrice = parseFloat($(this).text().replace(/[€\s]+/g, '').replace(',', '.'));
        if(isNaN(currentPrice) || currentPrice < 0 ) {
          /* can be more checks above, like $(this).text().indexOf('€') == -1 */
          throw new Error("Something wrong on calculating the total");
        }
        subTotalCurrentCategory += currentPrice;
      });
    
      // Store the current cat subtotal
      subTotals[uniqueCategoryNames[i]] = subTotalCurrentCategory;
    
      // Add the current subTotal to total
      totalPrice += subTotalCurrentCategory;
    
    }
    console.log({
      totalPrice: totalPrice,
      subTotals: subTotal
    });
    

    Btw. You can remove the both € and space (may also others) using one regex.