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
  • 183,571
  • 29
  • 224
  • 209
IWI
  • 1,528
  • 4
  • 27
  • 47

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
  • 3,362
  • 5
  • 27
  • 48
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
  • 802
  • 1
  • 4
  • 15