1. 程式人生 > >Lodash(陣列篇)

Lodash(陣列篇)

Lodash

chunk

_.chunk ( arr ,num )
從前往後按num切割arr

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

_.compact ( arr )
過濾arr內所有false, null, 0, "", undefined, and NaN .

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

_.concat ( arr , val )
val過濾調外一層的[]後拼入arr

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

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

console.log(array);
// => [1]

_.difference ( arr , [ val ] )
返回arr內與val內元素的差異

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

_.differenceBy ( arr , [ val ] , fun)
返回經過fun過濾後arr內與val內元素的差異

_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [1.2]

_.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
// => [{ 'x': 2 }]

_.differenceWith ( arr , [ val ] , fun

)
返回經過fun過濾後arr內與val內元素的差異

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];

_.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
// => [{ 'x': 2, 'y': 1 }]

drop

_.drop ( arr , num )
從前往後彈出arrnum個元素

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

_.dropRight ( arr , num )
從後往前彈出arrnum個元素

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

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

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

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

_.dropRightWhile ( arr , fun )
從後往前返回arr內滿足fun的元素val

_.dropRightWhile(users, function(o) { return !o.active; });
// => objects for ['barney']

_.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
// => objects for ['barney', 'fred']

_.dropRightWhile(users, ['active', false]);
// => objects for ['barney']

_.dropRightWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']

_.dropWhile ( arr , fun )
從前往後返回arr內滿足fun的元素val

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

_.dropWhile(users, function(o) { return !o.active; });
// => objects for ['pebbles']

_.dropWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['fred', 'pebbles']

_.dropWhile(users, ['active', false]);
// => objects for ['pebbles']

_.dropWhile(users, 'active');
// => objects for ['barney', 'fred', 'pebbles']

fill

_.fill ( arr , val , start , end )
從前往後依次將arr內元素替換為val
start為開始替換位置
end為結束替換位置
startend為空,則預設全部替換

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, 10], '*', 1, 3);
// => [4, '*', '*', 10]

_.findIndex ( arr , fun , num )