groupBy()

The groupBy linq operator returns a new linq object that contains "groupings" (objects with a property called "key" that contains the grouping key and a property called "values" that contains an array of the elements that are grouped under the grouping key) of the elements in the collection.

If the "element selector" function is given, then the objects in the "values" property of the grouping objects are the values projected from the elements in the originating collection by the element selector. If the element selector is not given, then the objects in the "values" property of the grouping objects are the elements of the originating collection, themselves.

The groupBy operator can also take a "key selector" function that is used to determine equality for grouping the elements.
var cars = [{make: 'Honda', model: 'Civic', color: 'blue'},
    {make: 'Acura', model: 'Integra', color: 'white'},
    {make: 'Toyota', model: 'Camry', color: 'white'},
    {make: 'Subaru', model: 'Forester', color: 'red'}];
    
// col1 = ['blue: (Honda Civic)', 'white: (Acura Integra, Toyota Camry)', 'red: (Subaru Forester)']
var col1 = $linq(cars).groupBy(
    "x => x.color",                 // key selector
    "x => x.make + ' ' + x.model")  // element selector
    .select("x => x.key + ': (' + x.values.join(', ') + ')'")
    .toArray();
    
var foods = ['carrot', 'CORN', 'cream cheese', 'brocolli', 'SPAGHETTI', 'strawberries'];

// col2 = ['c (3)', 'b (1)', 'S (2)']
var col2 = $linq(foods).groupBy(
    "x => x[0]",                                    // key selector
    null,                                           // no element selector
    "(x, y) => x.toLowerCase() == y.toLowerCase()") // key comparer
    .select("x => x.key + ' (' + x.values.length + ')'")
    .toArray();

Last edited Dec 18, 2013 at 6:25 PM by battousai999, version 4