【问题标题】:Group array of items by their distinct id按不同的 id 对项目数组进行分组
【发布时间】:2018-07-16 00:54:39
【问题描述】:

如何按衬衫尺寸重新排列我的数组:

[
  { 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" }]
];

【问题讨论】:

  • smallmediumlarge 字符串吗?它们是唯一允许的值吗?如第 0 组为small,第 1 组为medium,第 2 组为large
  • 可能有两个:{shirt_id:1, size: small}?
  • 是的,它们是字符串。
  • 对不起,我只编辑小问题 1。

标签: javascript json algorithm arraylist push


【解决方案1】:

您想要做的是将您的项目分成 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, size 'small' 怎么办?并且只显示一个
    • { shirt_id: 1, size: 'small' },{ shirt_id: 1, size: 'small' } 然后只显示一个
    • 你好 xianshenglu 你能再编辑一次你的答案吗? [ 1[ size: "small" }, { size: "medium" }, { size: "large" }], 2[{ size : "中" }], 3[ { 尺寸: "大" }] ];相反,每个尺寸的外面都有 shirt_id 的名称。
    • 你的预期输出是什么?
    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2013-03-12
    • 2014-10-27
    • 1970-01-01
    • 2020-02-29
    • 2021-11-14
    • 2020-04-25
    相关资源
    最近更新 更多