3

I have an array of array

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

How I get the sum length of all children array?

const length = 4 + 2 + 3

2 Answers 2

4

You can use _.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>

Sign up to request clarification or add additional context in comments.

1 Comment

The function passed to sumBy can be replaced with the property iteratee:sumBy(myArrays, 'length').
3

You can use _.forEach or _.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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.