使用reduce (javascript)在数组中添加数字对

Adding pairs of numbers in array with reduce (javascript)

本文关键字:添加 数字 数组 reduce javascript 使用      更新时间:2023-09-26

给定一个2D数组,我想将前一个内部数组的最后一个数字与下一个内部数组的第一个数字相加。

我设法达到了这样的地步:

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)

我现在想要将这些对相加以返回这个数组:

output = [9, 11, 10]

到目前为止,这是我所拥有的,它返回[3,6,4,7,9,1]。我想看看如何使用reduce来实现这一点,但也对for循环如何完成同样的事情感兴趣。

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

可以使用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)

不清楚输入数组的最后一个元素应该发生什么?您可以使用for..of循环,Array.prototype.entries()对数组的特定索引值求和。

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)

您可以这样做,使用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);