_.countBy(list, iteratee, [context])
排序一个列表组成一个组,并且返回各组中的对象的数量的计数。类似groupBy,但是不是返回列表的值,而是返回在该组中值的数目。就像EXCEL里的分类统计
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}
var parity = _.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
console.log(parity); //=> Object {odd: 3, even: 2}
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}
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}
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}
var list = [{x:'a'}, {x:'b'}, {x:'a'}];
var grouped = _.countBy(list, 'x');
console.log(grouped); //=> Object {a: 2, b: 1}
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}
var parity = _.countBy('abcab');
console.log(parity); //=> Object {a: 2, b: 2, c: 1}
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 {}
var parity = _.countBy('1234567', function (element, index, list) {
//请写下您的代码
});
console.log(parity); //=> Object {3n+1: 3, 3n+2: 2, 3n: 2}