当前位置: 首页 > 文档资料 > Lazy.js 英文文档 >

countBy

优质
小牛编辑
150浏览
2023-12-01

Creates a new ObjectLikeSequence containing the unique keys of all the elements in this sequence, each paired with the number of elements in this sequence having that key.

Signature

Sequence.countBy = function(keyFn) { /*...*/ }
Sequence.countBy = function countBy(keyFn) {
  return new CountedSequence(this, keyFn);
}
NameType(s)Description
keyFnFunction|string

The function to call on the elements in this sequence to obtain a key by which to count them, or a string representing a parameter to read from all the elements in this sequence.

returnsSequence

The new sequence.

Examples

function oddOrEven(x) {
  return x % 2 === 0 ? 'even' : 'odd';
}

var numbers = [1, 2, 3, 4, 5];

Lazy(numbers).countBy(oddOrEven)            // sequence: { odd: 3, even: 2 }
Lazy(numbers).countBy(oddOrEven).get("odd") // => 3
Lazy(numbers).countBy(oddOrEven).get("foo") // => undefined