Isabella Chen Isabella Chen - 1 year ago 57
Javascript Question

Adding pairs of numbers in array with reduce (javascript)

Given a 2D array, I want to add the last number of the preceeding inner array to the first number of the next inner array.

I managed to get up to the point where:

var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]] //this becomes...
output = [3,4,6,7,9,1] (edited typo)

I now would like to add the pairs up to return this array:

output = [9, 11, 10]

So far, this is what I have, and it returns [3,6,4,7,9,1]. I would like to see how reduced can be used for this, but also interested in how a for loop would accomplish the same thing.

var output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]]
output = output
newArr.push(currArr[0],currArr[currArr.length-1]) //[1,3,4,6,7,9]
return newArr
return output

Answer Source

Can use index argument of reduce

let output= [[1,2,3],[4,5,6],[7,8,9],[1,2,3]]; 
output = output
  .reduce((newArr, currArr, i, origArr) => {
    if (i > 0) {
      let prevArr = origArr[i - 1];
      newArr.push(currArr[0] + prevArr[prevArr.length - 1]);
    return newArr
  }, [])