Skip to content Skip to sidebar Skip to footer

Javascript Linq.js Groupby

I have the following JSON data in a Javascript function (it's simplified here): var data = [ { Expiry: '2013-01-02T00:00:00', EndDate: '2013-01-16T00:00:00', Category: 10, Amount

Solution 1:

Your key should be a composite key with both the Expiry and EndDate. Then you can include it in your result.

I wouldn't recommend trying to get your ideal result, creating results like that aren't in the spirit of what LINQ was made to do. Rather, you should collect items you are querying for.

var query = Enumerable.From(data)
    .GroupBy(
        "{ Expiry: $.Expiry, EndDate: $.EndDate }",
        null,
        "{ Expiry: $.Expiry, EndDate: $.EndDate, Categories: $$.Select('$.Category').ToArray(), Amounts: $$.Select('$.Amount').ToArray() }",
        "$.Expiry + '-' + $.EndDate"// compare selector needed
    )
    .ToArray();

However it is still possible to get your ideal result, but again, I would recommend not using this approach.

var query = Enumerable.From(data)
    .GroupBy(
        "{ Expiry: $.Expiry, EndDate: $.EndDate }",
        null,
        function (key, g) {
            return g.Aggregate({
                Expiry: key.Expiry,
                EndDate: key.EndDate
            }, function (result, item) {
                result['Category' + item.Category] = item.Amount;
                return result;
            });
        },
        "$.Expiry + '-' + $.EndDate"
    )
    .ToArray();

Post a Comment for "Javascript Linq.js Groupby"