0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Lodashの備忘録

Last updated at Posted at 2020-02-15

Lodashとは?

便利関数をまとめたJavaScriptライブラリです。
配列処理や単なる値の操作だけでなく、イベント処理を制限したりなど様々な関数があります。
ドキュメントを眺めていると面白い関数がたくさんあったので、気になった関数たちを紹介していきます。

_xor

  • 配列の同じ値をまとめて、新しい配列を返す
const arr2 = [2,3,4,4]
  const arr=[...arr2]

  const _arr = _.xor(arr)

  console.log(_arr)
// [2,3,4]

_has

  • 引数に渡したオブジェクトのキーを検索し、キーが存在すればtrueを返す
var object = { 'a': { 'b': 2 } };
_.has(object, 'a');
// => true

_sortBy

  • 第一引数に対象の配列、第二引数にソートしたいkey名

faker.js というダミーデータを作成してくれるライブラリを使用しています。

const targets: any[] = [];

for (let i = 1; i < 1500; i++) {
  targets.push({
    name: faker.company.companyName(),
    owner: faker.name.firstName()
  });
}
const res = _.sortBy(targets, ['name','owner']);

console.log(res);
// name,ownerの昇順で並び替えられる

_compact

  • falsyな値を取り除き、新しい配列を返す
const target = [0, 1, false, 2, '', 3]
const res = _.compact(target);

console.log(res)

// [1,2,3]

_flatten

  • 入れ子の配列を一階層なくす
const target = [['hello'],'world']
const res = _.flatten(target);

console.log(target)

// ["hello", "world"]

_pull

  • 第一引数に対象の配列、第二引数に取り除きたい値を渡し、配列を返す
for (let i = 1; i < 10; i++) {
  targets.push('トマト');
}

const _res = _.pull(targets, "トマト");

console.log(_res);

// []
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?