2017-08-24 130 views
1

的数组的长度我有阵Lodash - 如何总结阵列

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

数组我如何让所有的孩子阵列的总和长度是多少?

const length = 4 + 2 + 3 

回答

2

您可以使用_.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>

+1

传递给'sumBy'的函数可以用iteratee:'sumBy(myArrays,'length')'替换。 –

+0

谢谢@GruffBunny。我已经更新了答案 –

2

您可以使用_.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>