0

I am trying to add together an undetermined amount of arrays, but only add or reduce them item by item.

I cannot figure out how to make this work in ES6 javascript.

const arrayList = [
  [1, 2, 3],
  [1, 2, 3],
  [2, 2, 2]
];

const totalRow = arrayList.map((array) => {
  const total = [];
  array.map((number, i) => {
    total[i] = (total[i] == undefined ? 0 : total[i]) + number;
  });
  return total;
});


//Output is just 3 more arrays with no change, as it seems 
//the total variable resets to an empty array with each iteration.

//what i want is this output:
[4, 6, 8]

What am I doing wrong? I tried reduce method as well but came up empty

8
  • 3
    Use Array.reduce. Commented Jun 28, 2017 at 15:44
  • The dupe has my answer using Array.reduce(), which is perfect for this use-case. Array.map is not a right option in this case. Commented Jun 28, 2017 at 15:45
  • @PraveenKumar, the other dupe target matches better ... Commented Jun 28, 2017 at 15:50
  • @NinaScholz Lemme know the link or edit the links and add it yourself... :) Oh wow. You did it already. Commented Jun 28, 2017 at 15:54
  • 1
    thank you @praveenKumar that is perfect Commented Jun 28, 2017 at 16:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.