Count Array Items in Object of Arrays (combined count)

Viewed 82

Consider the following object:

const test = {
    foo: ['foo', 'bar', 'foobar'],
    bar: ['foo', 'bar', 'foobar']
    foobar: ['foo', 'bar', 'foobar']
};

How would one go about getting the combined count of all of the items within each of the arrays in the above object?

I am aware that I can do something along the lines of the following:

let count = 0;

Object.values(test).forEach(value => count += value.length);

console.log(count) // Expected result: 9

I am looking for a simpler (cleaner and hopefully one-liner) way of achieving this...

2 Answers

Just get the length of the flat values.

const test = {
    foo: ['foo', 'bar', 'foobar'],
    bar: ['foo', 'bar', 'foobar'],
    foobar: ['foo', 'bar', 'foobar']
};

let count = Object.values(test).flat().length;

console.log(count);

You could use the array reduce, which comes pretty close to a oneliner:

const count = Object.values(test).reduce((acc, cv) =>  acc + cv.length ,0)
Related