1

I have two arrays that I would like to map/recurse through and combine all the values into one array.

var array1 = ['steve', 'mike'];
var array2 = ['2020', '2019', '2018'];

The goal is to create an array of all the possible combinations:

['steve2020', 'steve2019', 'steve2018', 'mike2020', 'mike2019', 'mike2018']

I'm not sure if a map for for/next is appropriate or more efficient, but it's hurting my brain right now trying to decipher the recursion logic here. :) Any ideas are much appreciated.

evan
  • 43
  • 1
  • 7
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap with map() – epascarello Oct 11 '21 at 20:18
  • https://stackoverflow.com/questions/8936610/how-can-i-create-every-combination-possible-for-the-contents-of-two-arrays – epascarello Oct 11 '21 at 20:18

1 Answers1

0

You could use a combination of flatMap and map to go over both arrays, combine them and flatten the outcome array.

var array1 = ['steve', 'mike'];
var array2 = ['2020', '2019', '2018'];

const result = array1.flatMap((v) => array2.map((y) => `${v}${y}`));

console.log(result);
axtck
  • 3,707
  • 2
  • 10
  • 26