クイックリファレンス

Lodash チートシート

Lodash の総合リファレンス:コレクション操作、配列変換、カリー化・スロットリング・デバウンス、文字列・オブジェクト操作、メソッドチェーンを網羅。

· 公開日

Lodash は、配列・数値・オブジェクト・文字列を扱うためのモジュール性と高いパフォーマンスを備えたモダンな JavaScript ユーティリティライブラリです。

コレクション

コレクション関数は配列(Array)とオブジェクト(Object)のどちらに対しても統一的に動作します。

検索とフィルタリング

_.filter(list, (n) => n % 2 === 0);   // -> Array of matches
_.find(list, (n) => n % 2 === 0);     // -> First matching item
_.findLast(list, (n) => n % 2 === 0); // -> Last matching item
_.reject(list, (n) => n % 2 === 0);   // -> Array with matches excluded

深い階層のアクセスと変更

// Safe path access
_.get(object, 'users[0].name', 'Default');
_.get(object, ['users', 0, 'name']);

// Set value at deep path
_.set(object, 'users[0].name', 'Alice');

// Extract elements at paths
_.at({ a: [{ b: { c: 3 } }] }, ['a[0].b.c']); // -> [3]

反復処理と述語判定

_.forEach(list, (item, index) => { /* ... */ });
_.forEachRight(list, (item) => { /* ... */ });

_.map(list, (item) => item.id);

_.every(users, (u) => u.active); // -> Boolean (all match)
_.some(users, (u) => u.active);  // -> Boolean (at least one matches)

配列 (Arrays)

分割とスライス

_.chunk(['a', 'b', 'c', 'd'], 2);  // -> [['a', 'b'], ['c', 'd']]
_.compact([0, 1, false, 2, '', 3]); // -> [1, 2, 3] (removes falsy values)

_.drop([1, 2, 3, 4], 2);           // -> [3, 4]
_.take([1, 2, 3, 4], 2);           // -> [1, 2]

集合演算

_.uniq([2, 1, 2]);                       // -> [2, 1]
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], 'x'); // -> [{ x: 1 }, { x: 2 }]

_.difference([2, 1], [2, 3]);            // -> [1]
_.intersection([2, 1], [2, 3]);          // -> [2]
_.union([2], [1, 2]);                    // -> [2, 1]

関数 (Functions)

カリー化と部分適用

const greet = (greeting, name) => `${greeting}, ${name}!`;
const curriedGreet = _.curry(greet);

const sayHello = curriedGreet('Hello');
sayHello('Alice'); // -> "Hello, Alice!"

スロットリングとデバウンス

// Debounce: Wait for 300ms of inactivity before firing
const onSearch = _.debounce(searchApi, 300);

// Throttle: Fire at most once every 200ms
const onScroll = _.throttle(updateScrollPosition, 200);

// Once: Function that can only be invoked once
const initialize = _.once(setupApp);

キャッシュ(メモ化)

const fibonacci = _.memoize((n) => {
  return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

文字列 (Strings)

大文字・小文字と記法変換

_.camelCase('Foo Bar');   // -> "fooBar"
_.kebabCase('Foo Bar');   // -> "foo-bar"
_.snakeCase('Foo Bar');   // -> "foo_bar"
_.startCase('fooBar');    // -> "Foo Bar"
_.capitalize('fred');     // -> "Fred"

パディングとトリミング

_.pad('abc', 8);          // -> "  abc   "
_.padStart('abc', 6, '_'); // -> "___abc"
_.trim('  abc  ');        // -> "abc"
_.trim('-_-abc-_-', '_-'); // -> "abc"

オブジェクト (Objects)

キー・値・反転

_.keys({ a: 1, b: 2 });       // -> ['a', 'b']
_.values({ a: 1, b: 2 });     // -> [1, 2]
_.invert({ a: 'x', b: 'y' }); // -> { x: 'a', y: 'b' }

マージとクローン

// Shallow clone vs deep clone
const shallow = _.clone(user);
const deep = _.cloneDeep(user);

// Deep merge
_.merge({ a: [{ b: 1 }] }, { a: [{ c: 2 }] }); // -> { a: [{ b: 1, c: 2 }] }

// Pick and omit
_.pick(user, ['name', 'email']);
_.omit(user, ['password', 'salt']);

メソッドチェーン

_.chain() で複数の操作を連結し、.value() で結果の値を取り出します:

const youngestUsers = _(users)
  .filter((u) => u.active)
  .sortBy('age')
  .map((u) => `${u.name} is ${u.age}`)
  .head()
  .value();

リファレンス

関連テーマ