OctaviaLo
OctaviaLo

Reputation: 1396

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
    .reduce((newArr,currArr)=>{
    newArr.push(currArr[0],currArr[currArr.length-1]) //[1,3,4,6,7,9]
    return newArr
  },[])
    output.shift()
    output.pop()
return output

Upvotes: 0

Views: 318

Answers (3)

Sreekanth
Sreekanth

Reputation: 3130

You could do something like this, using reduce.

var input = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [1, 2, 3]
];


let output = [];
input.reduce((prevArr, currentArray) => {

  if (prevArr) {
    output.push(prevArr[prevArr.length - 1] + currentArray[0]);
  }
  return currentArray;
});
console.log(output);

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

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
  }, [])
console.log(output)

Upvotes: 3

guest271314
guest271314

Reputation: 1

Not clear what should occur at last element of input array? You can use for..of loop, Array.prototype.entries() to sum values of specific index of arrays.

let output = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
  [1, 2, 3]
];
let res = Array.from({
  length: output.length - 1
});
for (let [key, value] of output.entries()) {
  if (key < output.length - 1)
    res[key] = value[value.length - 1] + output[key + 1][0]
}
console.log(res)

Upvotes: 0

Related Questions