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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:25:38