0

I have an array, which is having arrays as it's values. What I need is an output that is having all array values.

Note : input array and it's elements(arrays) are not of fixed length.

Input :

array = 
[ 
  [a,b],
  [c,d,e],
  [f,g]
]

Output :

[
 {
  Header : a
  Children : 
  [
   {
    Header : c
    Children : 
     [
      Header : f
     ]
   },
  ]
 },
 {
  Header : a
  Children : 
  [
   {
    Header : c
    Children : 
     [
      Header : g
     ]
   },
  ]
 },
 {
  Header : a
  Children : 
  [
   {
    Header : d
    Children : 
     [
      Header : f
     ]
   },
  ]
 },
.
.
.
{
  Header : a
  Children : 
  [
   {
    Header : e
    Children : 
     [
      Header : g
     ]
   },
  ]
 },
 {
  Header : b
  Children : 
  [
   {
    Header : c
    Children : 
     [
      Header : f
     ]
   },
  ]
 },
 .
 .
 .
 .
 .
 {
  Header : b
  Children : 
  [
   {
    Header : e
    Children : 
     [
      Header : g
     ]
   },
  ]
 },
]

Basically it is like,

[a,c,f],
[a,c,g],
[a,d,f],
[a,d,g],
[a,e,f],
[a,e,g],
[b,c,f],
[b,c,g],
[b,d,f],
[b,d,g],
[b,e,f],
[b,e,g]

I have tried using for loop but couldn't get the desired output. Is there any way that we can achieve that result?

adiga
  • 34,372
  • 9
  • 61
  • 83
Jithin Joseph
  • 143
  • 3
  • 12
  • Stack Overflow is not a code writing service. Please provide a [mcve] of what you've tried and where you're stuck. – Emile Bergeron Oct 15 '19 at 18:03
  • @EmileBergeron I got what you are saying, but those for loops that i tried are now working properly. – Jithin Joseph Oct 15 '19 at 18:07
  • You can get the second output using this [Cartesian product of multiple arrays in JavaScript](https://stackoverflow.com/questions/12303989). Then you can loop thorugh the output array and create a nested object for each inner array using recursion – adiga Oct 15 '19 at 18:08
  • Also, it looks like the input in the question description doesn't match the output, or the logic behind is unclear, which makes it a lot harder to help. – Emile Bergeron Oct 15 '19 at 18:12

2 Answers2

0

You can create a Cartesian product of the 2D array first. Then, use reduceRight to create a nested object for each array in the Cartesian product

const data = [
  ["a", "b"],
  ["c", "d", "e"],
  ["f", "g"]
]

const cartesian = data.reduce((acc, curr) =>
  acc.flatMap(c => curr.map(n => [].concat(c, n)))
)

const tree = arr => arr.reduceRight((acc, Header) =>
    acc ? ({ Header, Children: [acc] }) : ({ Header })
, null)

const output = cartesian.map(tree)

console.log(JSON.stringify(cartesian))
console.log(output)
adiga
  • 34,372
  • 9
  • 61
  • 83
0
function join(arrayOfArrays) {
    let current = [[]];
    for (let array of arrayOfArrays) {
        current = current.flatMap(c=>array.map(a=>[...c, a]));
    }
    return current;
}