2

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?

4
  • @GuerricP, you are right about dimension, already updated the description. And "strange numbers" might be of any type, it doesn't matter. Commented Nov 23, 2020 at 20:13
  • What's the criteria if the data can be of any type? It's helpful to have a copy+pasteable example to work with, and 1.1.* isn't valid. Commented Nov 23, 2020 at 20:19
  • @Phix I'll update the example... But the idea is that each nested value should be converted into an array of all parents + this value, for example: [1] => [ [1] ]; [1, [2] ] => [ [1], [1, 2] ]; [1, [2], [3]] => [[1], [1, 2], [1, 3]] ... Commented Nov 23, 2020 at 20:47
  • Please include any research you've done on the subject and any attempts you've made based on that research. See How to Ask. Commented Nov 23, 2020 at 21:06

1 Answer 1

4

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]]]))

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

Comments

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.