A two-dimensional array, corresponding to the addition of subitems, to generate a new array

< H2 > question: js: is a two-dimensional array, and the corresponding subitems are added to generate a new array < / H2 >.

problem description

there is a two-dimensional array: traverse each item and accumulate the corresponding items to generate a new array;

Code

var arr = [[1,2,3,1],[2,3,4,2],[3,4,5,3]];
// 
var arr1 = [6,9,12,6];
Jun.02,2021

   let arr = [[1,2,3,1],[2,3,4,2],[3,4,5,3]];
   let arr1 = [];
   for(let i=0;i<arr[0].length;iPP){
       let sum = 0;
       for(let j=0;j<arr.length;jPP){
           sum += arr[j][i]
       }
       arr1.push(sum)
   }
   console.log("", arr1); // [6,9,12,6]

var arr = [[1,2,3,1],[2,3,4,2],[3,4,5,3]];
function trans (arr) {
  return arr.reduce((sum, item) => {
    item.forEach((cur, index) => {
      let num = sum[index] || 0
      sum[index] = num + cur
    })
    return sum
  }, [])
}
trans(arr)
Menu