Extract child arrays from nested arrays

  • A+
Category:Languages

I have nested array data and I would like to extract all nested arrays to be siblings of their parent. I am pretty close, but I am getting an extra empty array in the results and I cannot figure out where it is coming from or how to get rid of it.

Note: I would really like to understand why this is happening and how to get rid of it in my function, and not just a .filter(arr => arr.length) on my results list.

This is my attempt so far:

var arrs = [   [1, 2, [3, 4], 5],   [6, [7, 8, 9, [10, 11]]],   [12, 13],   [[14, 15], [16, 17]],   [[1], 4, [1, 1], 4] ];  // Desired Output // [ //   [1, 2, 5], //   [3, 4], //   [6], //   [7, 8, 9], //   [10, 11], //   [12, 13], //   [14, 15], //   [16, 17], //   [4, 4] //   [1] //   [1, 1] // ]  function extractArrays (arr) {   return arr.reduce((res, curr) => {     if (Array.isArray(curr)) {       res = res.concat(extractArrays(curr));     }     else {       res[0].push(curr);     }     return res;   }, [[]]); }  console.log(extractArrays(arrs)); // Results: // [  //   [],  <-- Where is this coming from? //   [ 1, 2, 5 ], //   [ 3, 4 ], //   [ 6 ], //   [ 7, 8, 9 ], //   [ 10, 11 ], //   [ 12, 13 ], //   [],  <-- Also here //   [ 14, 15 ], //   [ 16, 17 ], //   [ 4, 4 ], //   [ 1 ], //   [ 1, 1 ] ] // ]
.as-console-wrapper {   max-height: 100% !important; }

 


Element like [[14, 15], [16, 17]] will introduce a [] after recursion. This should be handled by checking length.

var arrs = [   [1, 2, [3, 4], 5],   [6, [7, 8, 9, [10, 11]]],   [12, 13],   [[14, 15], [16, 17]],   [[1], 4, [1, 1], 4] ];  function extractArrays (arr, acc=[]) {   if (arr.length == 0 ) return acc;   let pure = arr.filter(elm => !Array.isArray(elm));   if (pure.length > 0) {     acc.push(pure);   }        acc.concat(arr.filter(elm => Array.isArray(elm)).map(elm=> extractArrays(elm, acc)));    return acc; }  console.log(extractArrays(arrs));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: