按其不同的ID分组项目数组

时间:2018-02-06 03:15:20

标签: javascript json algorithm arraylist push

如何通过衬衫尺寸组织来重新安排我的阵列:

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

2 个答案:

答案 0 :(得分:2)

您要做的是将您的项目分组为3个桶。

根据数据,每个存储桶都由shirt_id - 1索引。

我们的想法是遍历每个项目,根据当前衬衫的内容填充适当的衬衫尺码。



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);




答案 1 :(得分: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);
&#13;
&#13;
&#13;