underscorejs-countBy学习

时间:2023-03-09 09:43:55
underscorejs-countBy学习

2.20 countBy

2.20.1 语法

_.countBy(list, iteratee, [context])

2.20.2 说明

排序一个列表组成一个组,并且返回各组中的对象的数量的计数。类似groupBy,但是不是返回列表的值,而是返回在该组中值的数目。就像EXCEL里的分类统计

  • list为 遍历的集合,如数组、对象、字符串、arguments等。
  • iteratee 迭代器,可以是一个function也可以字符串等。
  • iteratee 有三个参数 (element, index, list)
  • iteratee 需要有返回
  • context 执行上下文,改成iteratee内的this

2.20.3 代码示例

示例一:根据iteratee分类统计

var parity = _.countBy([1, 2, 3, 4, 5], function (num) {
return num % 2 === 0;
});
//符合条件的key为在true,不符合条件的key为false。
console.log(parity); //=> Object {false: 3, true: 2}

示例二:返回结果的Object指定key

var parity = _.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
console.log(parity); //=> Object {odd: 3, even: 2}

示例三:改变iteratee内的this

var parity = _.countBy('12345', function (num) {
console.log(this); //5 times => Object {no: 3}
return num > this.no;
}, {no : 3});
console.log(parity); //=> Object {false: 3, true: 2}

示例四:iteratee的三个参数& 不要忘记return

var parity = _.countBy('abc', function (element, index, list) {
console.log(element, index, list);
//=> a 0 abc
//=> b 1 abc
//=> c 2 abc
});
console.log(parity); //=> Object {undefined: 3}

2.20.4 iteratee可以是对象的属性

var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
var grouped = _.countBy(list, 'length');
console.log(grouped); //=> Object {3: 4, 4: 3, 5: 3}

2.20.5 iteratee可以是对象的key

var list = [{x:'a'}, {x:'b'}, {x:'a'}];
var grouped = _.countBy(list, 'x');
console.log(grouped); //=> Object {a: 2, b: 1}

2.20.6 iteratee可以是对象

var list = [{x:0, y:0}, {x:0, y:1}, {x:1, y:1}];
var grouped = _.countBy(list, {x:0});
console.log(grouped); //=> Object {true: 2, false: 1}

2.20.7 不传iteratee则以值进行分类统计

var parity = _.countBy('abcab');
console.log(parity); //=> Object {a: 2, b: 2, c: 1}

2.20.8 非集合返回{}

console.log(_.countBy(0)); //=> Object {}
console.log(_.countBy(NaN)); //=> Object {}
console.log(_.countBy(null)); //=> Object {}
console.log(_.countBy(undefined)); //=> Object {}
console.log(_.countBy(true)); //=> Object {}
console.log(_.countBy(false)); //=> Object {}

2.20.9 将字符串分成三组(坑)

var parity = _.countBy('1234567', function (element, index, list) {
//请写下您的代码
});
console.log(parity); //=> Object {3n+1: 3, 3n+2: 2, 3n: 2}