Search code examples
javascriptarrayslodash

How can I convert multidimensional array into 2 dimensions array?


Given multidimensional array (of any size and depth):

const multidimensionalArray = [1, [2, [3, [4, [5]]]], [6], [7, [8], [9]]];

I need to convert it into 2 dimensions array following example below (the idea is that each nested value should be converted into an array of all parents + this value).

Expected 2 dimensions array :

const twoDimensionsArray = [
  [1],
  [1, 2],
  [1, 2, 3],
  [1, 2, 3, 4],
  [1, 2, 3, 4, 5],
  [1, 6],
  [1, 7],
  [1, 7, 8],
  [1, 7, 9],
];

Could you please help me to solve the problem?


Solution

  • A recursive call for each nested array ought to do the trick.

    NOTE: The following may not be complete for your use case - your data needs to be in a specific order for this to work - but I think this should be clean enough as an example:

    const customFlatten = (arr, parents = [], output = []) => {
      for (const item of arr) {
        // If not an array...
        if (!Array.isArray(item)) {
          parents.push(item) // update parents for recursive calls
          output.push(parents.slice(0)) // add entry to output (copy of _parents)
    
        // If an array...
        } else {
          customFlatten(item, parents.slice(0), output) // recursive call
        }
      }
      return output
    }
    
    console.log(customFlatten([1, [2, [3, [4, [5]]]], [6], [7, [8], [9]]]))