Search code examples
javascriptarrayssub-array

How to merge sub-sub-arrays and add their lengths by the sub-array index?


I have an array with some sub-arrays (the code below describes a situation where each sub-array has two sub-sub-arrays, that number can vary, it could be five, but in this scenario we know they all would have five sub-arrays) with different lengths. Something like:

let arrayA = [
              [['a']            , ['b','c','d']],  //lengths  1  and  3 
              [['e','f','g','z'], ['h','i','j']],  //lengths  4  and  3
              [['k','l']        , ['m','n']]       //lengths  2  and  2 
                                                   //sums     7  and  8
             ]

We want to add the lengths of each sub-subarray by the index of the sub-array to which they belong:

let arrayB = [[7],[8]] 

What is the best way to achieve this?


Solution

  • You can use reduce to summarize the array. Use forEach to loop thru the inner array.

    let arrayA = [[["a"],["b","c","d"]],[["e","f","g","z"],["h","i","j"]],[["k","l"],["m","n"]]];
    
    let result = arrayA.reduce((c, v) => {
      v.forEach((o, i) => {
        c[i] = c[i] || [0];
        c[i][0] += o.length;
      })
      return c;
    }, []);
    
    console.log(result);