0

I have an array of arrays of integers that looks like this [[5, 3], [2,1], [4, 3]] and the output I am expecting is [8, 3, 7], but I seem to be missing something in my reduce function, as I'm getting an array of n undefined values like [undefined, undefined, undefined] since n=3

How can I get the sum of each array in the arrays and load that into an array?

const reducer = (accumulator, currentValue) => accumulator + currentValue;

const dayArray = [[3,5],[4,6],[8,2]];

const twoWeekArray = dayArray.map((day, index) => {
  return day.reduce(reducer);
});

console.log(twoWeekArray);
Ori Drori
  • 166,183
  • 27
  • 198
  • 186
IWI
  • 1,254
  • 3
  • 21
  • 39

2 Answers2

1

You forgot to return:

dayArray = [[3,5],[4,6],[8,2]];
twoWeekArray = dayArray.map((day, index) => {
    return day.reduce(function (a, b) {
        return a + b;
    });
});
Lior Pollak
  • 2,973
  • 5
  • 25
  • 46
0

Here you go...

const subject = [[5, 3], [2,1], [4, 3]]

const result = 
  subject.map((elem) => 
    elem.reduce((acum, current) =>
      acum = acum + current,
      0
    )
   )
   

console.log(result)
Jose Marin
  • 697
  • 1
  • 3
  • 13