繁体   English   中英

如何根据多个键对数据进行分组和聚合?

[英]How to group and aggregate data based on multiple keys?

给定以下数据:

var data = [
  { material: 100, color: "Blue", user: 424 },
  { material: 100, color: "Red", user: 424 },
  { material: 200, color: "Blue", user: 424 },
  { material: 200, color: "Blue", user: 424 },
  { material: 200, color: "Blue", user: 20 },
  { material: 200, color: "Blue", user: 20 },
  { material: 200, color: "Blue", user: 20 },
]

我必须实现具有以下结果的表数组:

// user | material | color | counter
// 424    100        Blue    1
// 424    100        Red     1
// 424    200        Blue    2
//  20    200        Blue    3

我试过类似的东西:(短代码)

const merged = data.reduce((r, { user, material, color, ...rest }) => {
  const key = `${user}-${material}-${color}`
  r[key] = r[key] || { user, material, color }
  r[key]["color"].push(rest)
  return r
}, {})

但无法实现解决方案。 任何帮助表示赞赏!

您可以只计算出现次数并获得一组对象作为结果;

 var data = [{ material: 100, color: "Blue", user: 424 }, { material: 100, color: "Red", user: 424 }, { material: 200, color: "Blue", user: 424 }, { material: 200, color: "Blue", user: 424 }, { material: 200, color: "Blue", user: 20 }, { material: 200, color: "Blue", user: 20 }, { material: 200, color: "Blue", user: 20 }], merged = Object.values(data.reduce((r, { user, material, color}) => { const key = `${user}-${material}-${color}`; r[key] = r[key] || { user, material, color, counter: 0 }; r[key].counter++; return r; }, {})); console.log(merged);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

下面的片段可以帮助你 go

 const data = [ { material: 100, color: "Blue", user: 424 }, { material: 100, color: "Red", user: 424 }, { material: 200, color: "Blue", user: 424 }, { material: 200, color: "Blue", user: 424 }, { material: 200, color: "Blue", user: 20 }, { material: 200, color: "Blue", user: 20 }, { material: 200, color: "Blue", user: 20 }, ] const counter = {} data.forEach(({ material, user, color }) => { counter[`${user}-${material}-${color}`] = (counter[`${user}-${material}-${color}`] || 0) + 1 }) console.log(counter)

使用lodash v4.17.15的解决方案:

const result = _.chain(data)
    .groupBy(({material, color, user}) => `${material}-${color}-${user}`)
    .map((items) => [
        items[0].user,
        items[0].material,
        items[0].color,
        items.length,
    ])
    .value();

原生js的解决方案:

function getHashObj({material, color, user}) {
    return `${material}-${color}-${user}`;
}

function getHashArr([user, material, color]) {
    return `${material}-${color}-${user}`;
}

const result = data.reduce((acc, item) => {
    const existed = acc.find((a) => getHashArr(a) === getHashObj(item));

    if (!existed) {
        return [ ...acc, [
            item.user,
            item.material,
            item.color,
            1,
        ]];
    }

    existed[3] += 1;

    return acc;
}, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM