-1

I am trying to combine multiple arrays elements into a single array.

To put it in better perspective let's say I have 3 arrays that look like this

array1 = ['test']
array2 = ['foo', 'foo_1', 'foo_2']
array3 = ['bar']

In the end I need a single array that looks like this.

finalArray = ['test.foo.bar', 'test.foo_1.bar', 'test.foo_2.bar'].

Each array might have different sizes and lengths. But the idea is the same. Kinda like a tree with each array being a branch of the other when combining.

Any help with this would be appreciated, thank you.

Nithish
  • 5,393
  • 2
  • 9
  • 24
jtoddp14
  • 1
  • 1
  • this looks like a form of brace expansion. there's an npm package that does something similar: https://github.com/juliangruber/brace-expansion – chiliNUT Oct 15 '20 at 17:01

1 Answers1

0

Using Array.map, you can map item by item from first array to third array.

const array1 = ['test'];
const array2 = ['foo', 'foo_1', 'foo_2'];
const array3 = ['bar'];

const result = array1.map((item1) => array2.map((item2) => `${item1}.${item2}`))
  .flat()
  .map((item) => array3.map((item3) => `${item}.${item3}`))
  .flat();
console.log(result);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39