Get cumulative length of array inside array of objects

I have been searching for quite a while but cannot find an answer to my issue. The problem is pretty simple; I have an array of objects, each containing another array of objects. I want to get the cumulative length of all arrays inside all objects.

Here is some sample data:

const items = [
    {
        id: 1,
        title: "Test 1",
        data: [
            {
                ...
            },
            {
                ...
            },
        ]
    },
    {
        id: 2,
        title: "Test 2",
        data: [
            {
                ...
            },
        ]
    }
]

In this sample, the length should be 3 since there is 2 objects inside the first object’s data property and 1 object inside the second object’s data property.

5 thoughts on “Get cumulative length of array inside array of objects”

  1. All you need to do is loop through all items you got, check the length of the data array of each item and add that length to a variable. Here is a working snippet:

    const items = [
        {
            id: 1,
            title: "Test 1",
            data: [
                {
                    
                },
                {
                    
                },
            ]
        },
        {
            id: 2,
            title: "Test 2",
            data: [
                {
                    
                },
            ]
        }
    ];
    // Initialize the count variable as 0
    var count = 0;
    // Pass through each item
    items.forEach((item)=>{
    // Adding the count of data of each item 
      count += item.data.length;
    });
    // Outputting the count
    console.log(count);
    Reply

Leave a Comment