How to sum elements at the same index in array of arrays into a single array?

前端 未结 6 980
陌清茗
陌清茗 2020-12-03 03:05

Let\'s say that I have an array of arrays, like so:

[
  [0, 1, 3],
  [2, 4, 6],
  [5, 5, 7],
  [10, 0, 3]
]

How do I generate a new array t

6条回答
  •  不思量自难忘°
    2020-12-03 04:08

    Assuming that the nested arrays will always have the same lengths, concat and reduce can be used.

        function totalIt (arr) {
            var lng = arr[0].length;
           return [].concat.apply([],arr)  //flatten the array
                    .reduce( function(arr, val, ind){ //loop over and create a new array
                        var i = ind%lng;  //get the column
                        arr[i] = (arr[i] || 0) + val; //update total for column
                        return arr;  //return the updated array
                    }, []);  //the new array used by reduce
        }
        
        var arr = [
          [0, 1, 3],
          [2, 4, 6],
          [5, 5, 7],
          [10, 0, 3]
        ];
        console.log(totalIt(arr));  //[17, 10, 19]

提交回复
热议问题