You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何实现两个数组的元素两两组合生成目标新数组

两个数组元素两两组合实现方案

你需要实现的是两个数组的笛卡尔积拼接,通过嵌套遍历即可完成,以下是可直接运行的代码:

基础实现(最易理解,基于map嵌套)

const arr1 = [ { value: "red", label: "Red" },{ value: "yellow", label: "Yellow" },{value: "Blue", label: "Blue" },]
const arr2 =[ { value: "s", label: "S" },{ value: "m", label: "M" },{ value: "l", label: "L" },]

const result = arr1.map(item1 => arr2.map(item2 => `${item1.value},${item2.value}`))

// 打印验证
console.log(result)
/* 输出符合你的预期:
[
  ["red,s","red,m","red,l"],
  ["yellow,s","yellow,m","yellow,l"],
  ["Blue,s","Blue,m","Blue,l"]
]
*/

reduce版本实现

如果你偏好使用reduce方法,可以用以下写法:

const resultWithReduce = arr1.reduce((acc, cur1) => {
  acc.push(arr2.map(cur2 => `${cur1.value},${cur2.value}`))
  return acc
}, [])

扩展:拍平为单个数组

如果需要将所有组合放在同一个一维数组中,在外层调用flat()方法即可:

const flatResult = arr1.map(item1 => arr2.map(item2 => `${item1.value},${item2.value}`)).flat()
// 输出:["red,s","red,m","red,l","yellow,s","yellow,m","yellow,l","Blue,s","Blue,m","Blue,l"]

常见错误说明

concat()方法仅能将两个数组合并为一个数组,不会处理内部元素的两两组合逻辑,因此无法满足需求。


内容的提问来源于stack exchange,提问作者zhiping foong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:39:04