How do I groupby and count json results using linqjs

633 views Asked by At

I would like to return some json from my web method that on the client side I can groupby and count using linqjs.

Some mock up data would look like....

var data = [
    { Name: "Bob" },
    { Name: "Bob" },
    { Name: "Ann" },
    { Name: "Charlie" },
    { Name: "Charlie" },
    { Name: "Charlie" }
];

I would like the result linqjs query to produce an array of objects....

var results = [
    { "Name": "Bob", "Count": 2 },
    { "Name": "Ann", "Count": 1 },
    { "Name": "Charlie", "Count": 3 }
];

I could then consume the results in a handlebars template that populates a select list on my html.

Here is an example of what I thought was getting close but my counting still is off....

var groupedNames = Enumerable.From(data).GroupBy("$.Name", null,
       function (key, g) {
           var result = {
               Name: key,
               Count: g.Sum(g + 1)
           }
           return result;
       }).ToArray();

alert(groupedNames);

Does anyone have any suggestions on how to accomplish this in linqjs?

1

There are 1 answers

0
Jeff Mercado On BEST ANSWER

To count the items in the group, use the Count() method.

var query = Enumerable.From(data)
    .GroupBy("$.Name", null, "{ Name: $, Count: $$.Count() }")
    .ToArray();