[英]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)
Let's just go ahead and use flatMap :)让我们继续使用 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()
:我喜欢使用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.