Lodash - 如何求和数组

时间:2017-08-24 04:24:00

标签: lodash

我有一个数组数组

const myArrays = [
    [ 1, 2, 3, 4], // length = 4
    [ 1, 2], // length = 2
    [ 1, 2, 3], // length = 3
];

我如何获得所有子数组的总长度?

const length = 4 + 2 + 3

2 个答案:

答案 0 :(得分:3)

您可以使用_.forEach_.reduce

const myArrays = [
    [ 1, 2, 3, 4], // length = 4
    [ 1, 2], // length = 2
    [ 1, 2, 3], // length = 3
];

var length = 0;

_.forEach(myArrays, (arr) => length += arr.length);

console.log('Sum of length of inner array using forEach : ', length);

length = _.reduce(myArrays, (len, arr) => { 
  len += arr.length;
  return len;
}, 0);

console.log('Sum of length of inner array using reduce : ', length);
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js'><</script>

答案 1 :(得分:3)

您可以使用_.sumBy

const myArrays = [
    [ 1, 2, 3, 4], // length = 4
    [ 1, 2], // length = 2
    [ 1, 2, 3], // length = 3
];

 var length = _.sumBy(myArrays, 'length');
console.log("length =", length);
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js'><</script>