2

I have the following array:

var data=  [{ "Id": 1, "Name": "NameOne"}
            { "Id": 2, "Name": "NameTwo"}
            { "Id": 2, "Name": "NameTwo"}]
            { "Id": 3, "Name": "NameThree"}]

Using linq.js I would like to return the following array:

var data=  [{ "Id": 1, "Name": "NameOne", Total: 1}
            { "Id": 2, "Name": "NameTwo", Total: 2}
            { "Id": 3, "Name": "NameThree", Total: 1}]

This means that I need to use GroupBy() with a Count(). I am not sure how to apply this using the linq.js reference.

J. Steen
  • 15,470
  • 15
  • 56
  • 63
nav
  • 509
  • 4
  • 19

2 Answers2

4

It's simple really:

var data = [
    { Id: 1, Name: 'NameOne' },
    { Id: 2, Name: 'NameTwo' },
    { Id: 2, Name: 'NameTwo' },
    { Id: 3, Name: 'NameThree' }
];
var query = Enumerable.From(data)
    // GroupBy (keySelector, elementSelector, resultSelector, compareSelector)
    .GroupBy(
        null, // (identity)
        null, // (identity)
        "{ Id: $.Id, Name: $.Name, Total: $$.Count() }",
        "'' + $.Id + '-' + $.Name"
    )
    .ToArray();

Use the overload of GroupBy() that includes the resultSelector, you'll want to grab the count of the grouped items (the second parameter).

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
2

You were probably having issues with the data not being uniform. a reduce flattens your data structure, and then you can manipulate it as you wish in the .Select().

var intialData = [[{ "Id": 1, "Name": "NameOne"}, { "Id": 2, "Name": "NameTwo"}, { "Id": 2, "Name": "NameTwo"}], { "Id": 3, "Name": "NameThree"}];         

var data = Enumerable.From(intialData.reduce(function(a,b) { return a.concat(b); }))
                     .GroupBy(function(item) { return item.Id; })
                     .Select(function(item) { return {"Id":item.source[0].Id, "Name":item.source[0].Name, "Total": item.source.length}; })
                     .ToArray();
kshreve
  • 310
  • 3
  • 14