LoginSignup
13
14

More than 5 years have passed since last update.

lodash

Last updated at Posted at 2017-06-10

デモ:https://codepen.io/mo4_9/pen/vZLdbq

並び替え

sortBy

ageで昇順

users = _.sortBy(users, 'age');

orderBy

'asc','desc'で昇順/降順が選べる

users = _.orderBy(users, 'age', 'desc');

reverse

ageで降順(メソッドチェーン)

users = _(users)
  .sortBy('age')
  .reverse()
  .value(); // 配列でなく1つのオブジェクトを返す場合は不要

shuffle

シャッフル

users = _.shuffle(users);

sample

ランダムに1つだけ取得

user = _.sample(users)

絞り込み

take

前から5つだけ取得

users = _.take(users, 5)

後ろから取得する場合はtakeRight

filter

age > 35 で絞り込む

users = _.filter(users, (obj) => {
  return obj.age > 35;
});

find

プロパティ、条件で絞り込む
複数該当するものがあったら最初に該当したものだけを取得

user = _.find(users, {user: 'fred', active: true})

includes

名前に'b'が含まれるユーザーを絞り込む

userContainB = _.filter(users, (obj) => {
  return _.includes(obj.user, 'b');
});

判定

inRange

'月'は1~12、'日'は1~31を取得したいとき

_.inRange(month, 1, 12 + 1);
_.inRange(today, 1, 31 + 1);

整形

padStart

ゼロ埋め
時間表示に使える

const hour = _.padStart(9,2,0);
const minute = _.padStart(5,2,0);
const second = _.padStart(3,2,0);
console.log(`${hour}:${minute}:${second}`); // 09:05:03

nth

たとえば http://sample.com/room/1/chat/2 の地点から roomId=1 を取得する

const roomId = _(location.href.split('/')).compact().nth(-3);

compact()はfalsyな値を削除

ループ

each

ObjectもNodeListもまわせるので便利。
古いiOSでNodeListにforEachが使えないなどのバグもよしなに吸収してくれるので、each処理はデフォルトでlodashを使うべき。

// NodeList
_.each(document.querySelectorAll('.item'), (elm,index) => {
  console.log(elm,index);
})
// Object
_.each({one: 1, two: 2, three: 3}, (value,key) => {
  console.log(key,value);
})

間引く

throttle

一定間隔以内での関数の再実行を禁止する

function throttle() {
  $('.throttle').append('throttle ');
}
$('#inputThrottle').on('click', _.throttle(throttle,1000))

debounce

処理が終了して、一定間隔経過したら関数の実行
再度処理が始まった場合はキャンセル

function debounce() {
  $('.debounce').append('debounce ');
}
$('#inputDebounce').on('click', _.debounce(debounce,1000))

参考
http://matsukaz.hatenablog.com/entry/2014/04/09/082410

13
14
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
13
14