jecorrales
jecorrales

Reputation: 270

sum elements of my collection with forEach

I'm getting a little problem when I'm trying to sum a little objects or elements from my collection, but in this way it is as if the data obtained were concatenated as strings of type string and the result it's:

Total:  05500000005

And the expected result it's:

Total:  15

This is my code forEach to go through the elements of my collection:

let total = 0;

data.forEach(element => {
  console.log("Element: ", element.cost_product);
  total += element.cost_product;
});
console.log("Total: ", total)

Upvotes: 0

Views: 75

Answers (2)

ccoeder
ccoeder

Reputation: 265

Is this what you looking for?

const total = [1, 2, 3].reduce((a, b) => a + b, 0);
console.log(total); // 6

In your case it's more convenient to do like this.

const total = [{cost_product: 1}, {cost_product: 2}, {cost_product: 5}].reduce(function (acc, obj) { return acc + obj.cost_product; }, 0);
console.log(total);

ES6

const total = [{ cost_product: 1 }, { cost_product: 2 }, { cost_product: 5 }].reduce((
    acc,
    obj,
  ) => acc + obj.cost_product,
  0);

console.log(total);

If cost_product is string you can try this

const total = [{ cost_product: "1" }, { cost_product: "2" }, { cost_product: "5" }].reduce((
    acc,
    obj,
  ) => acc + Number(obj.cost_product),
  0);

console.log(total);

With condition

  const total = [{ cost_product: 1 }, { cost_product: 2 }, { cost_product: 5 }].reduce((
    acc,
    obj,
  ) => {
    if (obj.cost_product >= 1 && obj.cost_product <= 4) {
      return acc + Number(obj.cost_product);
    }

    return acc;
  },
  0);

  console.log(total);

Upvotes: 3

Mark
Mark

Reputation: 137

I ran the code as followed:

let data = [{cost_product: 5},{cost_product: 1}]

let total = 0;

data.forEach(element => {
  console.log("Element: ", element.cost_product);
  total += element.cost_product;
});
console.log("Total: ", total)

And it works just fine. Check your cost_product type if it's really a number and not a string.

Upvotes: 1

Related Questions