Search code examples
linq.js

linq.js group by, aggregate multiple fields


I am trying to group my data by 2 properties, and sum two other properties for each group. My code is off just a bit, because I am getting the same sum for both the fields (value and quantity). What am I missing? Thanks!

The code -

var linq = Enumerable.from(data);
        var result = linq
            .groupBy(
                "{ pCo: $.portCo , sName: $.secName }",
                "$.value, $.quantity",
                "{ portCo: $.pCo, security: $.sName, value: $$.sum($.value), quantity: $$.sum($.quantity) }",
                "$.pCo + ' ' + $.secName")
            .toArray();

Solution

  • Ok, after n trials and (n-1) errors, got it to work with the following syntax:

    var linq = Enumerable.from(data);
            var result = linq
                .groupBy(
                    "{ pCo: $.portCo , sName: $.secName }",
                    null,
                    "{ portCo: $.pCo, security: $.sName, value: $$.sum('$.value'), quantity: $$.sum('$.quantity') }",
                    "$.pCo + ' ' + $.secName")
                .toArray();
    

    The rationale for the null is not clear to me, and i needed '$.x' quotes for the property names in the sum function.

    Inspiration for the solution from Jeff's answer here - https://stackoverflow.com/a/15647792/2011729