Roman Selin
Roman Selin

Reputation: 119

Sum of arrays inside for loop

I'm trying to get sum of each array inside for loop. My code now is something like this

for (var i = 1; i < 6; i++) {
    (function(i) {
        if ($(".brand_name-"+i).length > 0 ) {
            
            Array_new = parseInt ($(".price-" + i).text());
            someArray = $.trim (Array_new);
            var total = 0;
            for (var k = 0; k < someArray.length; k++) {
                total += someArray[k] << 0;
            }

            console.log(total);
        }

and HTML version of elements is

<strong class="product_price_send price-3">88.87</strong>
<strong class="product_price_send price-5">8.78</strong>
<strong class="product_price_send price-5">48.78</strong>

Problem is - its not showing sum of elements. Perhaps i need one more for loop inside for loop for an array?

Upvotes: 2

Views: 93

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

A small intro before getting to the full solution:

Sum all

Use Array.prototype.reduce()

const ELS_price  = document.querySelectorAll(".product_price_send");
// const ELS_prod_price = $(".product_price_send").get(); // if you use jQuery

const sum = [...ELS_price ].reduce((tot, el) => {
  tot += Number(el.textContent.trim());
  return tot;
}, 0);

console.log(sum)
<strong class="product_price_send price-3">88.87</strong>
<strong class="product_price_send price-5">8.78</strong>
<strong class="product_price_send price-5">48.78</strong>

Sum Pairing by data-* attribute

For you specific problem or pairing a brand to a price by some integer suffix.
The best thing you can do is pair the integer IDs using the data-* Attribute, and use the similar code as above:

$("[data-brand]").each(function() {

  const id = $(this).data("brand");

  const ELS_price = document.querySelectorAll(`[data-price="${id}"]`);

  const sum = [...ELS_price].reduce((tot, el) => {
    tot += Number(el.textContent.trim());
    return tot;
  }, 0);

  console.log(`${this.textContent} Sum: ${sum.toFixed(2)}£`)

});
<div data-brand="3">Foobar</div>
<div data-brand="5">Loremis</div>
<strong class="product_price_send" data-price="3">88.87</strong>
<strong class="product_price_send" data-price="5">8.78</strong>
<strong class="product_price_send" data-price="5">48.78</strong>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 3

Related Questions