将总数的百分比添加到结果中

时间:2014-10-30 13:13:12

标签: json linq.js

我需要有关此功能的帮助:

var ListFruits = Enumerable.From(data) 
    .GroupBy("$.Fruits", "", "d,v => { Fruits:d,NumberFruits:v.Sum('$.NumberFruits|0')}") 
    .Select(" $.Fruits+ ': ' + $.NumberFruits") 
    .ToArray();
// result is [apple: 2 , banana:5 , orange: 3]

我想为每个水果提供总数的百分比

执行此类操作的函数(其中total是所有水果的总和):

var ListFruits = Enumerable.From(data) 
    .GroupBy("$.Fruits", "", "d,v => { Fruits:d,NumberFruits:v.Sum('$.NumberFruits|0')}") 
    .Select(" $.Fruits+ ': ' + $.NumberFruits + 'is' + ($.NumberFruits/total)*100  ") 
    .ToArray();
// result is [apple: 2 is 20% , banana: 5 is 50% , orange: 3 is 30%]

1 个答案:

答案 0 :(得分:0)

嗯,你必须计算总数。使用=功能可以帮助保持清洁。

Let()

这会产生以下数组:

var data = [
    { Fruit: 'apple', Count: 2 },
    { Fruit: 'banana', Count: 5 },
    { Fruit: 'orange', Count: 3 }
];
var query = Enumerable.From(data)
    .Let(function (d) {
        var total = d.Sum("$.Count");
        return d.GroupBy("$.Fruit", "$.Count", function (f, g) {
            var sum = g.Sum(),
                percent = (sum / total) * 100;
            return f + ': ' + sum + ' is ' + percent + '%';
        });
    })
    .ToArray();