admin管理员组

文章数量:1400771

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.

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.

Share Improve this question edited Jan 28, 2015 at 16:23 J. Steen 15.6k15 gold badges58 silver badges64 bronze badges asked Jan 28, 2015 at 16:17 navnav 5094 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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, pareSelector)
    .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).

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();

本文标签: javascriptLinqJs Group By with CountStack Overflow