3

I am trying to group on 2 columns, and sum a third column, as shown here (paligap answer)- linqjs group by with a sum

My code is -

 var linq = Enumerable.From(treedata);


  var result2 = linq
      .Where(x => x.GlPartnerLevel2 != null)

      .GroupBy(
      "{ Gl1: $.GlPartnerLevel1 , Gl2: $.GlPartnerLevel2,}",
      null,
      function (key, g) {
          var result = {
              Name: key.Gl2,
              ParentName: key.Gl1,
              Value: g.Sum(function (y) { return y.Value | 0; })
          }
          return result;
      })

          .ToArray();

  console.log('result2', result2);

However - while it seems to be almost working, I am getting an array of 17 instead of 2 - so the grouping is perhaps off by a bit?

What am I doing wrong?

Fiddle with entire code and data here- http://jsfiddle.net/e3Lu9Lcs/2/

Community
  • 1
  • 1
Pundit
  • 33
  • 2
  • 5

1 Answers1

4

When grouping by composite keys, you need to provide a compare selector which converts the keys into a representation that can be compared (usually strings). Try this instead:

var query = Enumerable.From(data)
    .Where("$.GlPartnerLevel2 != null")
    .GroupBy(
        "{ PL1: $.GlPartnerLevel1 , PL2: $.GlPartnerLevel2 }",
        "$.Value | 0",
        "{ Name: $.PL2, ParentName: $.PL1, Value: $$.Sum() }",
        "$.PL1 + ' ' + $.PL2") // this must be included
    .ToArray();

updated fiddle

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • Brilliant, You rock. The fiddle of course works, and looks like the more elegant way to approach it... – Pundit Nov 24 '15 at 22:56
  • I take back my suggestion on using `JSON.stringify`, I don't know if it would be very reliable in general. Fortunately, the key is simple enough. – Jeff Mercado Nov 24 '15 at 23:05
  • Hmm... OK, then in that case I will go with the compare selector version. Thanks for the after thought too! – Pundit Nov 24 '15 at 23:49