Lodash - 如何对数组数组的长度求和

  • 本文关键字:数组 求和 Lodash lodash
  • 更新时间 :
  • 英文 :


我有一个数组数组

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

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

const length = 4 + 2 + 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>

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

最新更新