lodash速览:集合方法(一)

集合指(Array|Object)。数组

一、_.countBy(collection, [iteratee=_.identity]):按照必定规则统计数量。返回一个对象,key为迭代器运算的结果,value为匹配该结果的数量。ide

_.countBy(['one', 'two', 'three'], 'length');    // => { '3': 2, '5': 1 }
_.countBy([6.1, 4.2, 6.3], Math.floor);         // => { '4': 1, '6': 2 }

二、_.groupBy(collection, [iteratee=_.identity]):按照必定规则进行分组,用法雷同_.countBy()。返回一个对象,key为迭代器运算的结果,value为包含全部匹配项的数组。函数

_.groupBy(['one', 'two', 'three'], 'length');  // => { '3': ['one', 'two'], '5': ['three'] }
_.groupBy([6.1, 4.2, 6.3], Math.floor);        // => { '4': [4.2], '6': [6.1, 6.3] }

三、_.forEach(collection, [iteratee=_.identity]):简写为_.each(),相似原生Array的forEach方法。
相似方法:
_.forEachRight(collection, [iteratee=_.identity]):从右往左遍历。prototype

四、_.every(collection, [predicate=_.identity]):返回一个布尔值。若是集合的每一项都符合条件才返回true。相似原生Array的every方法。code

var users = [
  { 'user': 'barney', 'age': 36, 'active': false },
  { 'user': 'fred',   'age': 40, 'active': false }
];
_.every(users, ['active', false]);    // => true
_.every(users, 'active');        // => false

五、_.filter(collection, [predicate=_.identity]):筛选符合条件的项,返回一个数组,相似原生Array的filter方法。对象

_.filter([1,2,3,4,5,6], function(o) { return o>3; });        // => [4, 5, 6]

六、_.find(collection, [predicate=_.identity], [fromIndex=0]):照出符合条件的项,返回最早匹配的项或undefined。相似原生的Array的find方法。three

类似方法:
_.findLast(collection, [predicate=_.identity], [fromIndex=collection.length-1]):从后往前匹配。it

七、_.flatMap(collection, [iteratee=_.identity]):按照规则扩充数组,相似原生Array的flatMap方法。io

_.flatMap([1, 2], function (n) { return [n, n]; });        // => [1, 1, 2, 2]

相似方法:
_.flatMapDeep(collection, [iteratee=_.identity]):最后返回一维数组。
_.flatMapDepth(collection, [iteratee=_.identity], [depth=1]):知道返回数组的维度。ast

八、_.includes(collection, value, [fromIndex=0]):从集合的fromIndex开始查找,若是集合里包含value返回true,不然返回false。相似原生Array的includes方法。

_.includes([1, 2, 3], 1, 2);        // => false  从第2位查找1

九、_.invokeMap(collection, path, [args]):分别对集合的每一项调用指定方法,感受跟_.map()的做用差很少,迭代器调用方式略有不一样。

_.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');        // => [[1, 5, 7], [1, 2, 3]]
_.invokeMap([123, 456], String.prototype.split, '');    // => [['1', '2', '3'], ['4', '5', '6']]

相似方法:
_.map(collection, [iteratee=_.identity]):相似原生Array的map方法。

延伸:
lodash里不少方法均可以接收迭代器函数,像 _.every, _.filter, _.map, _.mapValues, _.reject, and _.some等。

十、_.keyBy(collection, [iteratee=_.identity]):按照必定规则进行分组,用法雷同_.groupBy()。返回一个对象,key为迭代器运算的结果,value为匹配迭代方法的一项,若是多个项都匹配,value则取最后一个匹配上的项。

var array = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'left1', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];
_.keyBy(array, function(o) {
  return String.fromCharCode(o.code);
});
// { 
//    a : {dir: "left1", code: 97},
//    d : {dir: "right", code: 100}
//  }
相关文章
相关标签/搜索