lodash数组常用方法

lodash是js的一个实用工具库,现在es6盛行,搭配loash工具库是最方便的一件事了。lodash内部封装了关于字符串,数组,对象一些常见数据类型的处理函数。它所有函数都不会在原有的数据上进行操作,而是复制出一个新的数据而不改变原有数据。
使用传统的js方法处理数据,我们难免会用到遍历取数,而使用loash工具库我们可以减少这一环节,所以还是安利一下。

下面整理的是项目上比较常用到的方法,主要是针对于数组。做一个属于自己的方法查找工具书吧。

使用之前要引用:

import {} from 'loash';

1.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])
[]

通常,我用此方法不仅可以剔除不需要的属性,也可以用于比较两个数组是否相同。

2.drop()
说明:数组元素删除
用法: _.drop(array,number),类似于原生js方法中的slice
参数说明:
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]

3.first()
说明:返回数组第一个元素.
用法:_.first(array)
如果数组为[]则返回undefined。

4.findIndex()
说明:查询元素序号,遍历数组,如果查询到了符合要求的第一个元素则返回序号,如果没查询到符合要求的元素则返回-1,类似于js中常用的indexof()方法
用法: .findIndex(array, [predicate=.identity], [thisArg])
参数说明:
array: 需要检查/遍历的数组
_.identity()方法返回传给它的第一个参数。
thisArg 需要搜索的索引

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

5.findLastIndex()
说明:类似于js中的lastIndexOf(), 其返回的序列号是符合要求的最后一个。
用法:.findLastIndex(array, [predicate=.identity], [thisArg]),见findIndex()方法。

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

7.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]

8.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

9.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

10.pull()
用法:_.pull(array, [values])
说明:移除值,直接在原数组上进行操作

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

11.last()
用法:_.last(array)
说明:返回参数数组的末尾元素

12.flattenDeep
用法:_.flattenDeep(array)
说明:递归的抹平嵌套数组

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

13.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]

14.xor()
用法:_.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这个函数应该是参数两个两个进行重复值消除的。如果n和n+1还有未消除的非重复值,那么会和n+2和n+3消除后保留下来的数组进行合并。

15.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位置的元素从逻辑上来说是同时移除的。避免了数组越界的问题。

16.remove()
用法:.remove(array, [predicate=.identity], [thisArg])
说明:移除元素,对原数组进行操作,并且返回移除元素的集合。
从参数可以看出来,参数的处理逻辑是类似于前面的dropRightWhile方法的。

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]

17.chunk 对数组进行分块的方法
用法: _.chunk(array,number) 根据number对array进行均等的分块,如果array不能被number平分,则会留下一个余下的块。

_.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']

18.compact()
说明:去除假值,将空值,0, NaN去除掉。
用法:_.compact(array)

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

>["a"]

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

>["a", "b"]

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

>[1, 2, 3]

19.dropRightWhile()
用法 .dropRightWhile(array,[predicate=.identity],[thisArg])
说明: 数组元素过滤
参数说明:
参数1:待处理的数组
参数2:可以是(Function|Object|string),会对数组的每个元素调用,会依赖于第三个参数【thisArg】 。
参数3:判断是否删除的谓词。

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']

参数predicate实际上是有几种可能的值类型的,根据参数predicate的值类型的不同,会有如下几种不同的处理:
1.function 此种情况下, 如果函数返回true,会把这一项drop掉。
2. string 如果参数predicate是一个属性名(string类型)的话,返回值将会是遍历此属性的value。然后根据value进行drop。并且如果参数3 thisArg也有值的话,则会比较thisArg和predicate的返回值的不同。根据比较的值来进行drop。
3. object 此种情况下。如果array中的某一项的属性和object中的属性一致,则返回true,否则就返回false.

20.initial()
说明:返回除了末尾元素的数组
用法:_.initial(array)

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

21.rest()
说明: 移除数组首元素 和initial相反
用法:_.rest(array)

22.intersection()
说明:返回新数组,其值就是数组参数的交集
用法:_.intersection([arrays])

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

23.slice 数组截取
用法:_.slice(array, [start=0], [end=array.length])

24.union()
说明:数组合并,去除重复值
用法:_.union([arrays])

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

25.uniq/unique
说明:数组去重
用法:_.uniq(array, [isSorted], [iteratee], [thisArg])

_.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 }]

26.keys()
说明:取出对象中所有的key值组成新的数组。

function Foo() {
  this.a = 1;
  this.b = 2;
}
Foo.prototype.c = 3;
 
_.keys(new Foo);
// => ['a', 'b'] (iteration order is not guaranteed)
_.keys('hi');
// => ['0','1']

类似object.keys(),返回对象中可枚举属性的数组。

以上只是列举了平时使用到比较多的方法,会不断更新,当然个人觉得js的方法有些也挺不错的,就不列举在此了。

猜你喜欢

转载自blog.csdn.net/sinat_32206135/article/details/84792240