lodash数组常用方法总结

1,去假值。 The values false, null, 0, “”, undefined, and NaN are falsey.

_.compact([0, 1, false, 2, , 3]);
// => [1, 2, 3]

2,合并成新数组

var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
 
console.log(other);
// => [1, 2, 3, [4]]
 
console.log(array);
// => [1]

3,删除数组中的元素

__.drop(array, [n=1])

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

4,取数组第一元素

_.head([1, 2, 3]);
// => 1
 
_.head([]);
// => undefined

5,取数组中所有值除最后一个

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

6,数组转为对象

_.fromPairs([[a, 1], [b, 2]]);
// => { a: 1, b: 2 }

7,把数组中的元素按照某种格式进行拼接

_.join([a, b, c], ~);
// => a~b~c

8,取数组的最后一个元素

_.last([1, 2, 3]);
// => 3

9,删除数组中的元素

var array = [a, b, c, a, b, c];
 
_.pull(array, a, c);
console.log(array);
// => [b, b]
var array = [a, b, c, a, b, c];
 
_.pullAll(array, [a, c]);
console.log(array);
// => [b, b]

注意:pullAll里面是数组

10,获取数组所有元素除第一个

_.tail([1, 2, 3]);
// => [2, 3]

11,数组合并留唯一值

_.union([2], [1, 2]);
// => [2, 1]

12,去除数组合重复的值

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

13,求两个数组的差集

_.xor([2, 1], [2, 3]);
// => [1, 3]
经验分享 程序员 微信小程序 职场和发展