underscorejs-groupBy学习
生活随笔
收集整理的這篇文章主要介紹了
underscorejs-groupBy学习
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2.18 groupBy
2.18.1 語(yǔ)法
_.groupBy(list, iteratee, [context])
2.18.2 說(shuō)明
把list分為多個(gè)集合,iterator為分組的依據(jù),返回值為Object
- list可以是數(shù)組、對(duì)象、字符串或arguments等
- iteratee為分組的依據(jù).
- iterator的參數(shù)(value, key, list)
- iterator如果是function需要返回值
- context可以改變iterator內(nèi)部的this
2.18.3 代碼示例
示例一:list可以是數(shù)組、對(duì)象、字符串或arguments等
var parity; var iteratee = function(value, key, list){return value % 2; // value % 2的結(jié)果是0或是1,所以key就是0或是1//return value % 2 === 0; //這樣子就變成了true或false };//list為數(shù)組 parity = _.groupBy([1, 2, 3], iteratee); console.log(parity); //=> {0:[2], 1:[1, 3]}//list為對(duì)象 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));示例二:iteratee可以全局的方法
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]}示例三:iteratee可以是list內(nèi)元素的屬性
var parity = _.groupBy(['a', 'b', 'cc'], 'length'); console.log(parity); //=> {1:['a', 'b'], 2:['c']}示例四:iteratee可以是list內(nèi),元素的key
這種情況其實(shí)是用的最多的。
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" // }] // }示例五:iteratee的參數(shù)
_.groupBy('abc', function(v, i, l){console.log(v, i, l);//=> a 0 abc//=> b 1 abc//=> c 2 abcreturn v; });示例六:context可以改變iterator內(nèi)部的this(坑)
_.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);2.18.4 list的特殊情況
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 {}2.18.5 將下列數(shù)組,按是否數(shù)字分類
var arr = [1, '1', '2', 2, '3', '3'];var parity = (function(arr){//寫下你的代碼 }(arr));console.log(parity); //=> {false:['1', '2', '3', '3'], true: [1, 2]}轉(zhuǎn)載于:https://www.cnblogs.com/kyo4311/p/5176217.html
總結(jié)
以上是生活随笔為你收集整理的underscorejs-groupBy学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 850 ANSI流明不虚标:小米投影仪2
- 下一篇: 现在也是只能谢谢随笔了,但是在以后收货的