lodash学习笔记之Array方法

今天周末在家无聊学习一下lodash. lodash目前的中文资料不多。并且api好像还被墙了。下面说一下lodash的arrary相关的方法。javascript

 

1. chunk   英 [tʃʌŋk]    顾名思义,是对数组进行分块的方法java

  • n. 大块;矮胖的人或物   

    用法: _.chunk(array,number)  根据number对array进行均等的分块,若是array不能被number平分,则会留下一个余下的块。node

    

_.chunk(['a','b','c','d'],-1);

//当 size<=1的时候,都是按1等分

> ['a','b','c','d']

//size=2

>[['a','b'],['c','d']]

//size=3

>[['a','b','c'],['d']]

//size>=4

>['a','b','c','d']

//不能这么传参数

_.chunk('a', 'b', 'c', 'd', 2)

>['a']

 

 

2. compact     去除假值api

  • adj. 紧凑的,紧密的;简洁的
  • vt. 使简洁;使紧密结合

 

    api: Creates an array with all falsey values removed. The values falsenull0""undefined, and NaN are falsey.数组

    用法:_.compact(array)ide

    

//很明显第一个参数被处理了,剩下的参数都被忽视了。
_.compact('a','b','');

>["a"]

_.compact(['a','b','']);

>["a", "b"]

_.compact([0, 1, false, 2, '', 3,NaN,undefined]);

>[1, 2, 3]

 

3. difference  从数组中过滤元素函数

 用法:_.difference(array,[values])

   参数说明: array:要被检查/过滤的数组。学习

                  values:要被在array中剔除的值的集合测试

   

//注意两个参数都应该是数组类型
_.difference([1,2,4],2) [1, 2, 4] _.difference([1,2,4],[2]) [1, 4] _.difference([1,2,4],[-1]) [1, 2, 4]
_.difference([1,2,4],[1,2,4])
[]

 

 4. drop  数组元素删除this

     用法:相似于原生js方法中的slice   _.drop(array,number)

     从头开始删除number个数组元素。number不传的话默认按1处理

     

_.drop([1, 2, 3]);
// → [2, 3]

_.drop([1, 2, 3], 2);
// → [3]

_.drop([1, 2, 3], 5);
// → []

_.drop([1, 2, 3], 0);
// → [1, 2, 3]

 

5. dropRight    数组元素删除

    用法几乎和drop同样,不一样的是从数组末尾开始删除。

 

6. dropRightWhile   数组元素过滤

    用法 _.dropRightWhile(array,[predicate=_.identity],[thisArg])

   -- Creates a slice of array excluding elements dropped from the end. 

   -- Elements are dropped until predicate returns false

   -- The predicate is bound to thisArg and invoked with three arguments: (value, index, array). 

    参数1:待处理的数组

    参数2:能够是(Function|Object|string),会对数组的每一个元素调用 。

    参数3:判断是否删除的谓词。  

    

_.dropRightWhile([1, 2, 3], function(n) {
  return n > 1;
});
// → [1]
var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// → ['barney', 'fred']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.dropRightWhile(users, 'active', false), 'user');
// → ['barney']

// using the `_.property` callback shorthand  此处的解释应该是要drop不存在active属性的对象。
_.pluck(_.dropRightWhile(users, 'active'), 'user');
// → ['barney', 'fred', 'pebbles']

 刚开始看的时候对第三条有点迷糊。怎么会一个都没有过滤掉呢?  查看了一下api.

 参数predicate其实是有几种可能的值类型的,根据参数predicate的值类型的不一样,会有以下几种不一样的处理:

 1. function  此种状况下, 若是函数返回true,会把这一项drop掉。这种状况下函数通常只有两个参数:array和function

 2. string    若是参数predicate是一个属性名(string类型)的话,则返回值将会是这次遍历此属性的value。而后根据value进行drop。

  而且若是参数3 thisArg也有值的话,则会比较thisArg和predicate的返回值的不一样。根据比较的值来进行drop。

  API:  If a property name is provided for predicate  the created _.property style callback returns the property value of the given element. 

  If a value is also provided for thisArg the created _.matchesProperty  style callback returns true for elements that have a matching property value, else false. 

 3. object  此种状况下。若是array中的某一项的属性和object中的属性一致,则返回true,不然就返回false. 

  API: If an object is provided for predicate  the created _.matches style callback returns true for elements that match the properties of the given object, else false.

  

  在测试的过程当中,发现一个奇怪的例子:

var obj=[{'a':0,'b':'sa'},{'a':2,'b':'sadff'},{'a':3,'b':21}];  _.pluck(_.dropRightWhile(obj,'a',0),'a');
[0, 2, 3]

 

 7. dropWhile  数组元素过滤

    和dropRightWhile是基本一致的,不一样点是从头至尾来进行计算的。

 

 8. fill  数组元素填充

     用法:  _.fill(array, value[start=0][end=array.length])

     从开始参数到结束参数,用value来替代或者填补数组元素。由于数组的下标是从0开始的,因此填充的范围是个左闭右开区间-填充的index范围包括start而不包括end.

     注意:此方法直接改变array,而不是返回一个数组。

var array = [1, 2, 3];

_.fill(array, 'a');
console.log(array);
// → ['a', 'a', 'a']

_.fill(Array(3), 2);
// → [2, 2, 2]

_.fill([4, 6, 8], '*', 1, 2);
// → [4, '*', 8]

 

9. findIndex  查询元素序号,遍历数组,若是查询到了符合要求的第一个元素则返回序号,若是没查询到符合要求的元素则返回-1.

    用法: _.findIndex(array[predicate=_.identity][thisArg])   _.identity()方法返回传给它的第一个参数。

    

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(chr) {
  return chr.user == 'barney';
});
// → 0

// using the `_.matches` callback shorthand
_.findIndex(users, { 'user': 'fred', 'active': false });
// → 1

// using the `_.matchesProperty` callback shorthand
_.findIndex(users, 'active', false);
// → 0

// using the `_.property` callback shorthand
_.findIndex(users, 'active');
// → 2

 

10. findLastIndex 相似于findIndex,只不过其返回的序列号是符合要求的最后一个。

      用法:_.findLastIndex(array[predicate=_.identity][thisArg])

 

11. first  返回数组第一个元素.

     用法:_.first(array)

     没什么好说的,若是数组为[]则返回undefined。

 

12. flatten 抹平嵌套数组

 用法:_.flatten(array[isDeep])

    isDeep为空或者false的状况下,只抹平第一层嵌套。为true的状况下,递归的进行抹平。

    

_.flatten([1, [2, 3, [4]]]);
// → [1, 2, 3, [4]]

// using `isDeep`
_.flatten([1, [2, 3, [4]]], true);
// → [1, 2, 3, 4]

 

13. flattenDeep 递归的抹平嵌套数组

用法:_.flattenDeep(array)

_.flattenDeep([1, [2, 3, [4]]]);
// → [1, 2, 3, 4]

 

14. indexOf

用法:_.indexOf(array, value[fromIndex=0])  从数组array中查询value的序号,参数3若是是true的话,执行二分查找。

_.indexOf([1, 2, 1, 2], 2);
// → 1

// using `fromIndex`
_.indexOf([1, 2, 1, 2], 2, 2);
// → 3

// performing a binary search
_.indexOf([1, 1, 2, 2], 2, true);
// → 2

 

15.initial  返回除了末尾元素的数组

用法:_.initial(array)

_.initial([1, 2, 3]);
// → [1, 2]

 

16. intersection 返回新数组,其值就是数组参数的交集

用法:_.intersection([arrays])

_.intersection([1, 2], [4, 2], [2, 1]);
// → [2]

17. last 返回参数数组的末尾元素

用法:_.last(array)

18. lastIndexOf  相似于indexOf,搜索方向为从末尾到开头

用法:_.lastIndexOf(array, value[fromIndex=array.length-1])

_.lastIndexOf([1, 2, 1, 2], 2);
// → 3

// using `fromIndex`
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// → 1

// performing a binary search
_.lastIndexOf([1, 1, 2, 2], 2, true);
// → 3

19.pull 移除值,直接在原数组上进行操做

用法:_.pull(array[values])

var array = [1, 2, 3, 1, 2, 3];

_.pull(array, 2, 3);
console.log(array);
// → [1, 1]

 

20. pullAt 按序号移除值,直接操做原数组而且返回移除的值组成的数组。

用法:_.pullAt(array[indexes])

var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);

console.log(array);
// → [5, 15]

console.log(evens);
// → [10, 20]

能够看出来,移除1,3位置的元素从逻辑上来讲是同时移除的。避免了数组越界的问题。

21.remove 移除元素,对原数组进行操做,而且返回移除元素的集合。

用法:_.remove(array[predicate=_.identity][thisArg])

从参数能够看出来,参数的处理逻辑是相似于前面的dropRightWhile方法的。

API:Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). 

var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 == 0;
});

console.log(array);
// → [1, 3]

console.log(evens);
// → [2, 4]

 

22. rest 移除数组首元素 和initial相反

用法:_.rest(array)

 

23.slice 数组截取

用法:_.slice(array[start=0][end=array.length])

那么和原生的slice有什么不一样呢?

API:This method is used instead of Array#slice to support node lists in IE < 9 and to ensure dense arrays are returned.

 

24.sortedIndex 在对一个有序数组array进行插入的时候,返回value应该插入的位置。从左向右计算。

用法:_.sortedIndex(array, value[iteratee=_.identity][thisArg])

 API:Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order. If an iteratee function is provided it is invoked for value and each element of array to compute their sort ranking. The iteratee is bound to thisArg and invoked with one argument; (value). 

_.sortedIndex([30, 50], 40);
// → 1

_.sortedIndex([4, 4, 5, 5], 5);
// → 2

var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };

// using an iteratee function
_.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
  return this.data[word];
}, dict);
// → 1

// using the `_.property` callback shorthand
_.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
// → 1

 

25. sortedLastIndex 用法相似于sortedindex,不一样的是从右至左计算插入的位置

用法:_.sortedLastIndex(array, value[iteratee=_.identity][thisArg])

_.sortedLastIndex([4, 4, 5, 5], 5);
// → 4

 

26. take 数组切片

用法:_.take(array[n=1])

API:Creates a slice of array with n elements taken from the beginning.

_.take([1, 2, 3]);
// → [1]

_.take([1, 2, 3], 2);
// → [1, 2]

_.take([1, 2, 3], 5);
// → [1, 2, 3]

_.take([1, 2, 3], 0);
// → []

 

27. takeRight 相似于take方法,执行方向不一样。 

用法:_.takeRight(array[n=1])

_.takeRight([1, 2, 3]);
// → [3]

 

28. takeRightWhile  

用法:_.takeRightWhile(array[predicate=_.identity][thisArg])

API:Creates a slice of array with elements taken from the end. Elements are taken until predicate returns falsey. The predicate is bound to thisArg and invoked with three arguments: (value, index, array). 

_.takeRightWhile([1, 2, 3], function(n) {
  return n > 1;
});
// → [2, 3]

var users = [
  { 'user': 'barney',  'active': true },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': false }
];

// using the `_.matches` callback shorthand
_.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
// → ['pebbles']

// using the `_.matchesProperty` callback shorthand
_.pluck(_.takeRightWhile(users, 'active', false), 'user');
// → ['fred', 'pebbles']

// using the `_.property` callback shorthand
_.pluck(_.takeRightWhile(users, 'active'), 'user');
// → []

 

29. takeWhile 相似于takeRightWhile 执行顺序相反

用法:_.takeWhile(array[predicate=_.identity][thisArg])

  

30.union 数组合并,去除重复值

用法:_.union([arrays])

_.union([1, 2], [4, 2], [2, 1]);
// → [1, 2, 4]

 

31.uniq/unique 数组去重 

用法:_.uniq(array[isSorted][iteratee][thisArg])

API:Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only the first occurence of each element is kept. Providing true for isSorted performs a faster search algorithm for sorted arrays. If an iteratee function is provided it is invoked for each element in the array to generate the criterion by which uniqueness is computed. The iteratee is bound to thisArg and invoked with three arguments: (value, index, array). 

_.uniq([2, 1, 2]);
// → [2, 1]

// using `isSorted`
_.uniq([1, 1, 2], true);
// → [1, 2]

// using an iteratee function
_.uniq([1, 2.5, 1.5, 2], function(n) {
  return this.floor(n);
}, Math);
// → [1, 2.5]

// using the `_.property` callback shorthand
_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// → [{ 'x': 1 }, { 'x': 2 }]

 

32. unzip  zip的逆运算,还原zip后的数组

用法:_.unzip(array)

var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
// → [['fred', 30, true], ['barney', 40, false]]

_.unzip(zipped);
// → [['fred', 'barney'], [30, 40], [true, false]]

var zipped2=_.zip(['fre','shike'],[30,40,50],[true,false]);
// →
[['fred', 30, true], ['barney', 40, false],[undefined,50,undefined]]
 

 

33. unzipWith  在数组重组的时候同时进行某些操做

用法:_.unzipWith(array[iteratee][thisArg])

[iteratee] (Function): The function to combine regrouped values.

var zipped = _.zip([1, 2], [10, 20], [100, 200]);
// → [[1, 10, 100], [2, 20, 200]]

_.unzipWith(zipped, _.add);
// → [3, 30, 300]

能够看出来,在unZip以后,由于iteratee是_.add函数,所以将unZip的结果进行了相加。

 

34. without  从数组中去除某些值

用法:_.without(array[values])

_.without([1, 2, 1, 3], 1, 2);
// → [3]

不一样于difference方法。其values参数能够不是一个数组,而是接在array参数以后的零散参数。

 

35.xor  对称消除重复值

API:Creates an array that is the symmetric difference of the provided arrays.

symmetric:对称的,均匀的。

用法:_.xor([arrays])

_.xor([1, 2], [4, 2]);
// [1, 4]

  _.xor([1,2],[3,4])
  // [1, 2, 3, 4]
  _.xor([1,2],[3,4,1])
  // [2, 3, 4]
  _.xor([1,2],[1,2])
  // []

若是更进一步探究:

_.xor([1,2],[1,2],[1])
[1]
_.xor([1,2],[1,2],[3,4])
[3, 4]
_.xor([1,2],[1,2],[1,4])
[1, 4]
_.xor([1,2],[1,2],[1,4],[1,4])
[]
_.xor([1,2],[1,2],[3,4,1])
[3, 4, 1]

是否是颇有趣? 推测若是前面的数组参数两两消除了,后面的数组即便有重复的元素,仍是会保留。

.xor([1,2],[1,2],[1,2])
[1, 2]

因此说,xor这个函数应该是参数两个两个进行重复值消除的。

_.xor([1,2],[1,2,3],[1,2])

若是n和n+1还有未消除的非重复值,那么会和n+2和n+3消除后保留下来的数组进行合并。

 

36. zip  数组分组

API:Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.

用法:_.zip([arrays])

_.zip(['fred', 'barney'], [30, 40], [true, false]);
// → [['fred', 30, true], ['barney', 40, false]]

若是zip的数组长度不一,则会这样

_.zip(['fred', 'barney'], [30, 40,50], [true, false]);
// → [['fred', 30, true], ['barney', 40, false],[undefined,50,undefined]]

 

37. zipObject  数组转对象   ._pair的反操做,

用法:_.zipObject(props[values=[]])

API:The inverse of _.pairs; this method returns an object composed from arrays of property names and values. Provide either a single two dimensional array, e.g. [[key1, value1][key2,value2]] or two arrays, one of property names and one of corresponding values.

Arguments

  1. props (Array): The property names.
  2. [values=[]] (Array): The property values.
_.zipObject([['fred', 30], ['barney', 40]]);
// → { 'fred': 30, 'barney': 40 }

_.zipObject(['fred', 'barney'], [30, 40]);
// → { 'fred': 30, 'barney': 40 }

能够看出来,当只有一个数组参数的时候,最底层的数组被解读为[key,value]

当有两个数组参数的时候,这两个数组分别被解释为name和key的集合。 而后被组装为object返回。

 

38.  zipWith  相似于unzipWith函数

用法:_.zipWith([arrays][iteratee][thisArg])

_.zipWith([1, 2], [10, 20], [100, 200], _.add);
// → [111, 222]

 

以上就是lodash v3.8的全部数组方法,对比ECMAScript 5中的数组方法。确实在一些特殊操做上简化了咱们的一些特殊处理。

相关文章
相关标签/搜索