Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

groupBy(selectors[, comparer, arg])

suckgamoni edited this page · 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.

Syntax

Parameters

selectors

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.

key
A function to extract the key for each element.

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

result
A function to create a result value from each group.

comparer

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

arg

An external argument

Return Value

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


Example

// 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
*/
Something went wrong with that request. Please try again.