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)
Let's just go ahead and use flatMap :)
const arr1 = ['XYZ', 'ABC'] const arr2 = ['EUR', 'USD'] const result = arr1.flatMap(val => arr2.map(e => `${val}/${e}`)) console.log(result)
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!
You could reduce an array of arrays and map the parts.
This approach works for more than two arrays as well.
var array1 = ['XYZ', 'ABC'], array2 = ['EUR', 'USD'], result = [array1, array2].reduce((a, b) => a.flatMap(v => b.map(w => `${v}/${w}`))); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.