如何在JavaScript中分组元素并生成笛卡尔积
实现按属性组分组并生成笛卡尔积的通用逻辑
1. 按attributeGroupId分组
先通过Array.prototype.reduce将原数组按attributeGroupId分组,得到以组ID为键、对应属性数组为值的对象,再转为二维数组:
const originalArray = [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name: '24K'}, {attributeGroupId:2, attributeId: 12, name: 'Square'} ]; // 分组逻辑 const grouped = Object.values(originalArray.reduce((acc, item) => { const key = item.attributeGroupId; if (!acc[key]) { acc[key] = []; } acc[key].push(item); return acc; }, {})); console.log(grouped); // 输出: // [ // [ { attributeGroupId: 2, attributeId: 11, name: 'Diamond' }, { attributeGroupId: 2, attributeId: 12, name: 'Square' } ], // [ { attributeGroupId: 1, attributeId: 9, name: '916' }, { attributeGroupId: 1, attributeId: 1, name: '24K' } ] // ]
2. 生成通用笛卡尔积
实现通用的笛卡尔积生成函数,将分组后的数组传入,最后映射成目标格式:
// 通用笛卡尔积函数 function cartesianProduct(arrays) { return arrays.reduce((acc, current) => { return acc.flatMap(prev => current.map(item => [...prev, item])); }, [[]]); } // 生成笛卡尔积并转换格式 const result = cartesianProduct(grouped).map(combination => { const attributeIds = combination.map(item => item.attributeId).join('-'); const names = combination.map(item => item.name).join('-'); return { attributeId: attributeIds, name: names }; }); console.log(result); // 输出: // [ // { attributeId: '11-9', name: 'Diamond-916' }, // { attributeId: '11-1', name: 'Diamond-24K' }, // { attributeId: '12-9', name: 'Square-916' }, // { attributeId: '12-1', name: 'Square-24K' } // ]
该逻辑支持任意数量的属性组,无论运行时attributeGroupId有多少个,都能正确生成对应的笛卡尔积结果。
内容的提问来源于stack exchange,提问作者Bhavesh
相关产品推荐
相关产品推荐

