按照它们的不同ID对项目数组进行分组

6

我该如何重新排列我的数组,按照衬衫尺码进行组织:

[
  { shirt_id: 1, size: "small" },
  { shirt_id: 1, size: "medium" },
  { shirt_id: 1, size: "large" },
  { shirt_id: 2, size: "medium" },
  { shirt_id: 3, size: "large" }
];

期望输出:

[
  [1, { size: "small" }, { size: "medium" }, { size: "large" }],
  [2, { size: "medium" }],
  [3, { size: "large" }]
];

“small”,“medium”和“large”是字符串吗?它们是唯一允许的值吗?就像组0是“small”,组1是“medium”,组2是“large”一样? - nem035
有可能出现两个这样的吗:{shirt_id:1, size: small}? - xianshenglu
是的,它们是字符串。 - Yamoshi Wolverine
抱歉,我只是稍微修改了问题1。 - Yamoshi Wolverine
2个回答

2
你需要做的是将你的物品分成3个桶。
根据数据,每个桶都由 shirt_id - 1 索引。
想法是遍历每个项目,根据当前衬衫的id填充相应的桶以适合衬衫尺寸。

const data=[{shirt_id:1,size:"small"},{shirt_id:1,size:"medium"},{shirt_id:1,size:"large"},{shirt_id:2,size:"medium"},{shirt_id:3,size:"large"}];

const getBucketNumFromShirtId = shirtId => shirtId - 1;

const result = data.reduce((buckets, item) => {
  // determine bucket index from the shirt id
  const bucketNum = getBucketNumFromShirtId(item.shirt_id);

  // if the bucket corresponding to the bucket num doesn't exist
  // create it and add the shirt id as the first item
  if (!Array.isArray(buckets[bucketNum])) {
    buckets[bucketNum] = [item.shirt_id];
  }

  // add the shirt size into the appropriate bucket
  buckets[bucketNum].push({ size: item.size });

  // return buckets to continue the process
  return buckets;
}, []);

console.log(result);


2

尝试这个:

let data = [{ shirt_id: 1, size: 'small' }, { shirt_id: 1, size: 'small' },
    { shirt_id: 1, size: 'medium' },
    { shirt_id: 1, size: 'large' },
    { shirt_id: 2, size: 'medium' },
    { shirt_id: 3, size: 'large' }
];

let result = data.reduce(function(result, obj) {
    let idPos = result.map(v => v[0]).indexOf(obj.shirt_id);

    if (idPos > -1) {
        let sizeArr = result[idPos].slice(1).map(obj => obj.size);
        
        if (sizeArr.indexOf(obj.size) < 0) {
            result[idPos].push({ 'size': obj.size });
        }
    } else {
        result.push([obj.shirt_id, { 'size': obj.size }]);
    }

    return result;
}, []);

console.log(result);


先生,如果我们有相同的重复 shirt_id:1,尺寸为“小”,该怎么办?并且只显示一个。 - Yamoshi Wolverine
{ shirt_id: 1, size: 'small' },{ shirt_id: 1, size: 'small' } 然后只显示一个。 - Yamoshi Wolverine
先生路您好,您能否再编辑一次您的答案,最后一次了。将以下代码: [ { size: "small" }, { size: "medium" }, { size: "large" } ], [ { size: "medium" } ], [ { size: "large" } ] 改为每个尺码都有衬衫ID名称在外部。 - Yamoshi Wolverine
你期望的输出是什么? - xianshenglu
让我们在聊天中继续这个讨论 - Yamoshi Wolverine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接