Reputation: 509
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.
Upvotes: 2
Views: 7741
Reputation: 134841
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).
Upvotes: 4
Reputation: 330
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();
Upvotes: 2