![](/img/trans.png)
[英]Faster way to find an occurrence of 2-Dimensional array of keywords with frequency value
[英]What's a more effective or shorter way to group, then get a percentage value of a 2-dimensional array using underscore?
我是使用下划線的新手,因此我確定有更好的方法可以執行以下操作:
var data = [
{"from": "Belgium", "to": "Belgium", "count": "0"},
{"from": "Belgium", "to": "France", "count": "3"},
{"from": "Belgium", "to": "Germany", "count": "5"},
{"from": "France", "to": "Belgium", "count": "4"},
{"from": "France", "to": "France", "count": "9"},
{"from": "France", "to": "Germany", "count": "1"},
{"from": "Germany", "to": "Belgium", "count": "7"},
{"from": "Germany", "to": "France", "count": "2"},
{"from": "Germany", "to": "Germany", "count": "5"},
]
至
var formatted_data = [
[0, 0.08333333333, 0.13888888888],
[0.11111111111, 0.25, 0.02777777777],
[0.19444444444, 0.05555555555, 0.13888888888]
]
基本上,將其按“從”分組,然后將每個計數除以總數(在本例中為36)。 我並不是真的想對國家/地區進行硬編碼,但是數據將始終包含“從”和“到”的每個組合。
這是我的代碼(但我知道它可能會更好):
var total = _.pluck(data, "count").reduce(function(memo, value) { return memo + parseInt(value, 10); }, 0);
data = _.groupBy(data, function(value) { return value.from; });
formatted_data = [];
_.each(data, function(value, key, list) {
formatted_data.push(_.pluck(data[key], "count").map(function(value) { return value/total; }));
});
這個怎么樣? (假設您已經計算了total
的值。)
var formatted_data = _(data).map(function (e) {
return {from: e.from, v: parseInt(e.count,10)/total};
}).groupBy(function(e) {
return e.from;
}).values().map(function (a) {
return _.pluck(a, 'v');
}).value();
此解決方案簡化了總計計算和按國家/地區分組:
var total = _.reduce(data, function(memo, value){
return memo + parseInt(value.count, 10);
}, 0);
var counts = _.chain(data)
.groupBy('from')
.map( function(country){
return _.map(country, function(value){
return parseInt(value.count,10) / total;
});
})
.value();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.