0

Given a simple array of nested arrays like this:

[
  ['a','b',],
  ['c','d'],
  ['e']
]

I'm looking to concatenate the values from each element and create an array like this:

['.a.c.e','.a.d.e','.b.c.e','.b.d.e']

This is just a simple example but in reality there could be more than 3 nested arrays and any number of elements within them.

Seems like it should be relatively simple, but I just can't wrap my brain around it, can anyone help?

the_lar
  • 63
  • 9
  • It's not clear how your input array relates to your expected output. Could you expand on what you are trying to do – Brett Gregson Oct 24 '19 at 08:37
  • I'm basically trying to construct a jquery class selector where the output has every combination of input values. So you can see in my question, there are 2 x 2 x 1 possible combinations, so 4 results. Obviously if there were more elements in each array or more arrays, there would be more possible combinations. I basically need an array with all the possible combinations – the_lar Oct 24 '19 at 08:51

1 Answers1

0

Since the array length is unknown, the best way is to use recursion:

function conc(input) {
  const output = [];
  function _conc(input, partial) {
    if (input.length === 0) {
      return output.push(partial);
    }
    const [first, ...rest] = input;
    first.forEach(itm => {
      _conc(rest, partial + "." + itm)
    });
  }
  _conc(input, "");
  return output;
}

const input = [
  ['a','b',],
  ['c','d'],
  ['e']
]

console.log(conc(input))

or with flatMap:

function conc(input) {
  const [first, ...rest] = input;
  return rest.length === 0
    ? first.map(itm => "." + itm)
    : first.flatMap(itm => conc(rest).map(_itm => "." + itm + _itm));
}

const input = [
  ['a','b',],
  ['c','d'],
  ['e']
]

console.log(conc(input))

or with reduce:

const input = [
  ['a','b',],
  ['c','d'],
  ['e']
]

console.log(
  input.reduce((acc, a) => acc.flatMap(i1 => a.map(i2 => i1 + "." + i2)), [""])
)
marzelin
  • 10,790
  • 2
  • 30
  • 49