繁体   English   中英

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

[英]Adding pairs of numbers in array with reduce (javascript)

给定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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM