LoginSignup
22
19

More than 5 years have passed since last update.

lodash ちょっとマニアックだけど便利な関数

Last updated at Posted at 2018-06-28

JavaScript を使っているなら lodash は大変便利なのですが、関数が多すぎてどれ使ったらいいのか解りづらいのが難点です。

ここではその中からマニアックだけど便利な関数を紹介します。

Math 系

小数点を指定しての引き上げ/切り捨て/四捨五入

ceil, floor, round

_.ceil(number, 2) // 小数点第2位で切り上げ
_.floor(number, 2)
_.round(number, 2)
  • 標準の Math の関数では小数点第n位の指定ができなかった。

配列を渡しての集計

max, min, sum, mean

_.max([1, 2, 3])  // -> 3
_.min([1, 2, 3])  // -> 1
_.sum([1, 2, 3])  // -> 6
_.mean([1, 2, 3]) // -> 2
  • Math の関数では引数に展開して渡す必要があった。

オブジェクトのプロパティで集計

maxBy, minBy, sumBy, meanBy

_.maxBy([{a:1}, {a:2}, {a:3}], 'a')   // -> {a:3}
_.minBy([{a:1}, {a:2}, {a:3}], 'a')   // -> {a:1}
_.sumBy([{a:1}, {a:2}, {a:3}], 'a')   // -> 6
_.meanBy([{{a:1}, {a:2}, {a:3}], 'a') // -> 2
  • 'a' の代わりに o => o.a のように関数を渡すことも可。

Number 系

数値を強制的に範囲にとどめる

clamp

_.clamp(-10, -5, 5) // => -5
_.clamp(10, -5, 5) // => 5

ランダム値を得る

random

_.random(0, 5)        // => 0~5 の整数値
_.random(0, 5, true)  // => 0~5 の浮動小数
_.random(1.2, 5.2)    // => 1.2~5.2 の浮動小数

String 系

変則的な大文字/小文字

camelCase, kebabCase, snakeCase, capitalize

_.camelCase('Foo Bar')     // => 'fooBar'
_.camelCase('foo-bar')     // => 'fooBar'
_.camelCase('__FOO_BAR__') // => 'fooBar'

_.kebabCase('Foo Bar')     // => 'foo-bar'
_.kebabCase('fooBar')      // => 'foo-bar'
_.kebabCase('__FOO_BAR__') // => 'foo-bar'

_.snakeCase('Foo Bar')     // => 'foo_bar'
_.snakeCase('fooBar')      // => 'foo_bar'
_.snakeCase('--FOO-BAR--') // => 'foo_bar'

_.capitalize('FRED')       // => 'Fred'

パディング

pad, padStart, padEnd

_.pad('abc', 8, ' ')      // => '  abc   ' // 前後に埋める
_.padStart('abc', 8, ' ') // => '     abc' // 前に埋める
_.padEnd('abc', 8, ' ')   // => 'abc     ' // 後に埋める

エスケープ

escape, unescape, escapeRegExp

_.escape('fred, barney, & pebbles')
// => 'fred, barney, & pebbles'

_.unescape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'

_.escapeRegExp('[lodash](https://lodash.com/)')
// => '\[lodash\]\(https://lodash\.com/\)'

Util 系

ユニーク番号生成

uniqueId

_.uniqueId('contact_') // => 'contact_104'
_.uniqueId() // => '105'

Lang 系

どんなものも配列としてうけとる

castArray

_.castArray([0, 1]) // -> [0, 1]  // 配列ならそのまま
_.castArray(0)      // -> [0]
_.castArray(null)   // -> [null]
  • 戻り値が1個のときのみ配列じゃなくなっちゃう API を使ってるときになどに便利。

クローン

clone, cloneDeep

var cloned = _.clone(value) // 浅いクローン
var cloned = _.cloneDeep(value)

lodash関連の記事

22
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19