-3

I Want to sum all price values of an array for duplicated elements in array... I have this array:

var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]]

And this is what I want:

var products = [["product_1", 10, "hamburger"],["product_2", 17, "cola"]]

Can any good soul help me?

Viktor
  • 13
  • 3

1 Answers1

1

I think you meant to write ........, ["product_1", 4, "hamburger"]].

You can use Object.values() and Array#reduce methods as in the following demo:

const 
  products = [
    ["product_1", 6, "hamburger"],
    ["product_2", 10, "cola"],
    ["product_2", 7, "cola"],
    ["product_1", 4, "hamburger"]
  ],

  output = Object.values(
    products.reduce(
      (acc, [id, num, name]) =>
      ({ ...acc,
        [id]: [id, (acc[id] && acc[id][1] || 0) + num, name]
      }), {}
    )
  );

console.log(output);
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • 1
    Pretty gnarly considering all the advanced syntax and `reduce` being combined. Some comments would really help readers understand what's happening. – Ruan Mendes Sep 13 '22 at 19:38