3

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 2

9

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);

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

4 Comments

Exactly the sort of thing I am looking for! Thank you!! Will test now
Works perfectly - will accept as soon as I can. This is exactly why I posted this question. I searched Google for certain keywords but could not find anything. The flat method is something I have not come across before... Thank you very much!
Since the question is tagged ES2017 specifically I'd like to point out that Array.prototype.flat() was actually introduced in the ES2019 specification.
@PatrickRoberts - ah, very interesting! I only tagged ES2017 because I wanted to encourage modern solutions. ES2019 is even better :-D
2

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)

1 Comment

I like this solution since reduce() is the conventional method choice for aggregation and avoids creating a temporary array like flat().

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.