groupBy
优质
小牛编辑
131浏览
2023-12-01
Creates a new ObjectLikeSequence comprising the elements in this one, grouped together according to some key. The value associated with each key in the resulting object-like sequence is an array containing all of the elements in this sequence with that key.
Signature
Sequence.groupBy = function(keyFn, valFn) { /*...*/ }
Sequence.groupBy = function groupBy(keyFn, valFn) { return new GroupedSequence(this, keyFn, valFn); }
Name | Type(s) | Description |
---|---|---|
keyFn | Function|string | The function to call on the elements in this sequence to obtain a key by which to group them, or a string representing a parameter to read from all the elements in this sequence. |
valFn | Function|string | (Optional) The function to call on the elements in this sequence to assign to the value for each instance to appear in the group, or a string representing a parameter to read from all the elements in this sequence. |
returns | ObjectLikeSequence | The new sequence. |
Examples
function oddOrEven(x) { return x % 2 === 0 ? 'even' : 'odd'; } function square(x) { return x*x; } var numbers = [1, 2, 3, 4, 5]; Lazy(numbers).groupBy(oddOrEven) // sequence: { odd: [1, 3, 5], even: [2, 4] } Lazy(numbers).groupBy(oddOrEven).get("odd") // => [1, 3, 5] Lazy(numbers).groupBy(oddOrEven).get("foo") // => undefined Lazy(numbers).groupBy(oddOrEven, square).get("even") // => [4, 16] Lazy([ { name: 'toString' }, { name: 'toString' } ]).groupBy('name'); // => sequence: { 'toString': [ { name: 'toString' }, { name: 'toString' } ] }