1

I have an "object of objects of arrays" and I simply need to get the total count of elements in the "bottom level" arrays ...so with the example below, I need to return 19 (counting elements a to s):

var arr={ 'AA': { 'aa': ['a','b'],
                  'bb': ['c','d'],
                  'cc': ['e','f'],
                  'dd': ['g','h'] }, 
          'BB': { 'ee': ['i','j'],
                  'ff': ['k','l'] }, 
          'CC': { 'gg': ['m','n'],
                  'hh': ['o','p'],
                  'ii': ['q','r','s'] } };

I have it working with this but it ain't pretty:

var cnt=0;
for(var f0 in arr){
  for(var f1 in arr[f0]){
    cnt+=arr[f0][f1].length;
  }
}

It's probably best to use map and reduce but can't quite wrap my head around it. There are similar Q+A's (like this) but I couldn't quite find one that fits this situation.

Thanks!

1
  • You can't use map or reduce on your datastructure, because this two functions are from the Array.prototype and your datastructe is an array in an object in an object as you stated correct. Or just for the inner arrays? so to replace that part --> cnt+=arr[f0][f1].length;? Commented May 18, 2022 at 7:54

1 Answer 1

1

By using Object.values to access the values associated with each key, you can use a nested reduce to count all the bottom level elements:

var arr={ 'AA': { 'aa': ['a','b'],
                  'bb': ['c','d'],
                  'cc': ['e','f'],
                  'dd': ['g','h'] }, 
          'BB': { 'ee': ['i','j'],
                  'ff': ['k','l'] }, 
          'CC': { 'gg': ['m','n'],
                  'hh': ['o','p'],
                  'ii': ['q','r','s'] } };
                  
const cnt = Object.values(arr)
  .reduce((c, o) => c + Object.values(o)
    .reduce((c, a) => c + a.length,
            0),
          0);
  
console.log(cnt)

  

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

4 Comments

Thanks! Compressed: cnt=Object.values(arr).reduce((c,o)=>c+Object.values(o).reduce((c,a)=>c+a.length,0),0)
@ashleedawg no worries - glad I could help. I wrote it out expansively just to (hopefully) make it more obvious what it was doing.
absolutely -- and appreciated! My comment wasn't intended as an improvement.
@ashleedawg no worries - not taken as such.

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.