对对象数组进行分组的最有效方法

对对象数组进行分组的最有效方法

本文介绍了对对象数组进行分组的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对数组中的对象进行分组的最有效方法是什么?

What is the most efficient way to groupby objects in an array?

例如,给定以下对象数组:

For example, given this array of objects:

[
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]

我正在表格中显示此信息.我想对不同的方法进行分组,但是我想对这些值求和.

I’m displaying this information in a table. I’d like to groupby different methods, but I want to sum the values.

我将Underscore.js用于其groupby函数,这很有用,但并不能解决所有问题,因为我不希望它们分裂"但合并",更像SQL 方法.

I’m using Underscore.js for its groupby function, which is helpful, but doesn’t do the whole trick, because I don’t want them "split up" but "merged", more like the SQL group by method.

我正在寻找的东西将能够总计特定的值(如果需要).

What I’m looking for would be able to total specific values (if requested).

因此,如果我对Phase进行了分组,我希望收到:

So if I did groupby Phase, I’d want to receive:

[
    { Phase: "Phase 1", Value: 50 },
    { Phase: "Phase 2", Value: 130 }
]

如果我对Phase/Step进行了分组,则会收到:

And if I did groupy Phase / Step, I’d receive:

[
    { Phase: "Phase 1", Step: "Step 1", Value: 15 },
    { Phase: "Phase 1", Step: "Step 2", Value: 35 },
    { Phase: "Phase 2", Step: "Step 1", Value: 55 },
    { Phase: "Phase 2", Step: "Step 2", Value: 75 }
]

是否为此提供了有用的脚本,还是我应该坚持使用Underscore.js,然后循环遍历生成的对象以自己进行总计?

Is there a helpful script for this, or should I stick to using Underscore.js, and then looping through the resulting object to do the totals myself?

推荐答案

如果要避免使用外部库,则可以像这样简单地实现groupBy()的原始版本:

If you want to avoid external libraries, you can concisely implement a vanilla version of groupBy() like so:

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

console.log(groupBy(['one', 'two', 'three'], 'length'));

// => {3: ["one", "two"], 5: ["three"]}

这篇关于对对象数组进行分组的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:52