This is the original array I want to convert:
const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];
and this is the result I want:
const result = [
[1, 2, 3, 8, 9],
[4, 5, 10, 11, 14, 15],
[6, 7, 12, 13]
];
This separation is based on the depth of the array
6
Answers
You can iterate through items in array and checking they depth:
This is a good fit for a recursive solution. We’ll write a function that handles the elements of the array it’s given if they aren’t arrays, or calls itself if they are, passing along the target array and the target index in it. So elements at the top level we’ll add to an array at index 0, but the first time we recurse we’ll add to an array at index 1, etc.
Live example:
A good way to do that is to iterate over the baseArray and use a recursive function to complete the result variable depending on the depth you are browsing
You could take a recursive approach by handing over an index for level and result array.