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
相关产品推荐
相关产品推荐

