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

前端 未结 6 984
陌清茗
陌清茗 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:06

    Using Lodash 4:

    function sum_columns(data) {
      return _.map(_.unzip(data), _.sum);
    }
    
    var result = sum_columns([
      [1, 2],
      [4, 8, 16],
      [32]
    ]);
    
    console.log(JSON.stringify(result));

    For older Lodash versions and some remarks

    Lodash 4 has changed the way _.unzipWith works, now the iteratee gets all the values passed as spread arguments at once, so we cant use the reducer style _.add anymore. With Lodash 3 the following example works just fine:

    function sum_columns(data) {
      return _.unzipWith(data, _.add);
    }
    
    var result = sum_columns([
      [1, 2],
      [4, 8, 16],
      [32],
    ]);
    
    console.log(JSON.stringify(result));

    _.unzipWith will insert undefineds where the row is shorter than the others, and _.sum treats undefined values as 0. (as of Lodash 3)

    If your input data can contain undefined and null items, and you want to treat those as 0, you can use this:

    function sum_columns_safe(data) {
      return _.map(_.unzip(data), _.sum);
    }
    
    function sum_columns(data) {
      return _.unzipWith(data, _.add);
    }
    
    console.log(sum_columns_safe([[undefined]])); // [0]
    console.log(sum_columns([[undefined]]));      // [undefined]

    This snipet works with Lodash 3, unfortunately I didn't find a nice way of treating undefined as 0 in Lodash 4, as now sum is changed so _.sum([undefined]) === undefined

提交回复
热议问题