Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge and distribute the first array over the second one in JavaScript?

What would be the elegant way to achieve the result demonstrated in the snippet below.

I'm merging two arrays into a new array by distributing each element of the first array on to the second array.

arr1 = ['XYZ', 'ABC']
arr2 = ['EUR', 'USD']
result = ['XYZ/EUR', 'XYZ/USD', 'ABC/EUR', 'ABC/USD']

let symbolList = [];
SYMBOLS = ['XYZ', 'ABC']
PAIRS = ['EUR', 'USD']
SYMBOLS.map(s => symbolList.push(PAIRS.map(p => s + '/' + p)));
let processSymbols = symbolList.flat();
console.log(processSymbols)
like image 524
mbilyanov Avatar asked Nov 29 '25 16:11

mbilyanov


2 Answers

const arr1 = ['XYZ', 'ABC']
const arr2 = ['EUR', 'USD']

const result = arr1.flatMap(val => arr2.map(e => `${val}/${e}`))

console.log(result)
like image 189
Max Avatar answered Dec 02 '25 04:12

Max


I like to use reduce():

const arr1 = ['XYZ', 'ABC'];
const arr2 = ['EUR', 'USD'];

const result = arr1.reduce((a, c) => {
  arr2.forEach(e => a.push(`${c}/${e}`));  
  return a;
}, []);

console.log(result);

I hope that helps!

like image 24
norbitrial Avatar answered Dec 02 '25 05:12

norbitrial