简体   繁体   English

如何在 JavaScript 中合并和分配第一个数组到第二个数组?

[英]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.

相关问题 如何将数组与第一个是普通数组,第二个是 JavaScript 中的数组配对? - How do I pair arrays with the first one being a normal array and second one an array of arrays in JavaScript? 在数组上均匀分布 boolean 值(Javascript) - Distribute boolean values uniformly over array (Javascript) 将第二个数组的元素随机分布在第一个数组中 - distribute the elements of second array inside the first array randomly javascript 用第二个数组值替换第一个数组值。 第一个数组长度为 2,第二个数组长度为 7 - javascript replace first array value with second array value. First array length is 2 and second one length is 7 如何在一个数组中合并数组数组(在JavaScript中)? - How to merge array of arrays in one array (in JavaScript)? 如何通过点击第一个按钮将第二个按钮传递给javascript函数 - how to pass second button on click over the first button to a javascript function 如何将几个数组运算符合并为一个? Javascript - How to merge few array operators in one ? Javascript for循环中的数组与第二个for循环数组javascript合并 - array in for loop merge with second for loop array javascript 如何在 javascript 中的一个数组中合并另一个数组对象中的数组 - how to merge array inside another array objects in one array in javascript 完成JavaScript中的第一个回调后,如何执行第二个回调? - How to perform the second callback after the completion first one in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM