_.groupBy(list, iteratee, [context])
把list分为多个集合,iterator为分组的依据,返回值为Object
var parity;
var iteratee = function(value, key, list){
return value % 2; // value % 2的结果是0或是1,所以key就是0或是1
//return value % 2 === 0; //这样子就变成了true或false
};
//list为数组
parity = _.groupBy([1, 2, 3], iteratee);
console.log(parity); //=> {0:[2], 1:[1, 3]}
//list为对象
parity = _.groupBy({a:1, b:2, c:3}, iteratee);
console.log(parity); //=> {0:[2], 1:[1, 3]}
//list为字符串
parity = _.groupBy('123', iteratee);
console.log(parity); //=> {0:[2], 1:[1, 3]}
//list为arguments
(function(){
parity = _.groupBy(arguments, iteratee);
console.log(parity); //=> {0:[2], 1:[1, 3]}
}(1, 2, 3));
var parity;
//iteratee可以是全局的方法
parity = _.groupBy([1, 1.4, 1.6, 1.9], Math.floor);
console.log(parity); //=> {1 : [1, 1.4, 1.6, 1.9]}
parity = _.groupBy([1, 1.4, 1.6, 1.9], Math.ceil);
console.log(parity); //=> {1 : [1], 2: [1.4, 1.6, 1.9]}
var parity = _.groupBy(['a', 'b', 'cc'], 'length');
console.log(parity); //=> {1:['a', 'b'], 2:['c']}
这种情况其实是用的最多的。
var array = [{
"type": "stream",
"price": "3.99",
"id": "13nee"
}, {
"type": "stream",
"price": "2.99",
"id": "8ejwj"
}, {
"type": "buy",
"price": "3.99".
"id": "9akwk"
}];
var parity = _.groupBy(array, 'type');
console.log(parity);
//=>
// {
// stream: [{
// "type": "stream",
// "price": "3.99",
// "id": "13nee"
// }, {
// "type": "stream",
// "price": "2.99",
// "id": "8ejwj"
// }],
// buy: [{
// "type": "buy",
// "price": "3.99".
// "id": "9akwk"
// }]
// }
_.groupBy('abc', function(v, i, l){
console.log(v, i, l);
//=> a 0 abc
//=> b 1 abc
//=> c 2 abc
return v;
});
_.groupBy('1', function(v, i, l){
console.log(this);//=> Object {txt: "moe"}
}, {txt : 'moe'});
_.groupBy('1', function(v, i, l){
console.log(this ===1 ); //true or false?
}, 1);
console.log(_.groupBy(null)); //=> Object {}
console.log(_.groupBy(undefined)); //=> Object {}
console.log(_.groupBy(NaN)); //=> Object {}
console.log(_.groupBy(true)); //=> Object {}
console.log(_.groupBy(false)); //=> Object {}
var arr = [1, '1', '2', 2, '3', '3'];
var parity = (function(arr){
//写下你的代码
}(arr));
console.log(parity);
//=> {false:['1', '2', '3', '3'], true: [1, 2]}