groupBy(selectors[, comparer, arg])

suckgamoni edited this page May 15, 2013 · 1 revision

Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. Key values are compared by using a specified comparer, and the elements of each group are projected by using a specified function.




Type: {
    key: function (value, key, arg)
    value: function (value, key, arg)
    result: function (value, key, arg)
A JSON object which contains selectors. Can be null. All selectors are optional.

A function to extract the key for each element.

A function to map each source element to an element in the result.

A function to create a result value from each group.


Type: function(key1, key2, arg): boolean
An equality comparer to compare keys with.


An external argument

Return Value

A collection of elements of type TResult where each element represents a projection over a group and its key.


// Create a list of pets.
var petsList = [
    { name: "Barley", age: 8.3 },
    { name: "Boots", age: 4.9 },
    { name: "Whiskers", age: 1.5 },
    { name: "Daisy", age: 4.3 } ];

// Group Pet.Age values by the Math.Floor of the age.
// Then project an anonymous type from each group
// that consists of the key, the count of the group's
// elements, and the minimum and maximum age in the group.
var query = from(petsList).groupBy({
    value: "$age",
    key: "Math.floor($age)",
    result: function(ages, baseAge) {
        return {
            key: baseAge,
            count: ages.count(),
            min: ages.min(),
            max: ages.max()

// Iterate over each anonymous type.
query.each(function(result) {
    console.log("\nAge group: " + result.key);
    console.log("Number of pets in this age group: " + result.count);
    console.log("Minimum age: " + result.min);
    console.log("Maximum age: " + result.max);

/*  This code produces the following output:

    Age group: 8
    Number of pets in this age group: 1
    Minimum age: 8.3
    Maximum age: 8.3

    Age group: 4
    Number of pets in this age group: 2
    Minimum age: 4.3
    Maximum age: 4.9

    Age group: 1
    Number of pets in this age group: 1
    Minimum age: 1.5
    Maximum age: 1.5