Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - 对对象数组进行分组的最有效方法(Most efficient method to groupby on an array of objects)

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.

(我想对不同的方法进行分组,但是我想对这些值求和。)

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.

(我将Underscore.js用于其groupby函数,这很有用,但并不能解决所有问题,因为我不希望它们“分裂”而是“合并”,更像SQL group by方法。)

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

(我正在寻找的是能够总计特定值(如果需要)。)

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

(因此,如果我按Phase进行groupby,则希望收到:)

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

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

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

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

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?

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

  ask by Rail24 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

 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"]} 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...