0

I have a list of sounds like so:

[ 
  [ 'b', 'v' ],
  [ 'a' ],
  [ 'n', 't' ]
]

I need to produce a list of all combinations there sounds can make. The desired output is:

[
  'ban',
  'van',
  'bat',
  'vat'
]

The best I have been able to come up with so far is a hard-coded solution but the solution must be flexible to accommodate any length of array. Any ideas? thx

danday74
  • 52,471
  • 49
  • 232
  • 283

1 Answers1

1

You could recursively traverse the combinations and yield the results through a generator:

 function* combine([head, ...tail], previous = []) {
   for(const v of head) {
     if(tail.length) {
       yield* combine(tail, [...previous, v]);
     } else yield [...previous, v];
  }
}

// Then just do
console.log(
  [...combine(["bv", "a", "nt"])].map(it => it.join(""))
);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151