1
的數組的長度我有陣Lodash - 如何總結陣列
const myArrays = [
[ 1, 2, 3, 4], // length = 4
[ 1, 2], // length = 2
[ 1, 2, 3], // length = 3
];
數組我如何讓所有的孩子陣列的總和長度是多少?
const length = 4 + 2 + 3
的數組的長度我有陣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>
傳遞給'sumBy'的函數可以用iteratee:'sumBy(myArrays,'length')'替換。 –
謝謝@GruffBunny。我已經更新了答案 –