LoginSignup
1
2

More than 3 years have passed since last update.

Lodashを使って配列の差分を取得する

Last updated at Posted at 2021-02-27

はじめに

開発しているアプリでGoogleカレンダーの予定を同期した際にデータベースに保存するようにしています。しかし、カレンダー側で削除した予定がデータベースには残っていて、表示されてしまっていました。
削除済みの予定をデータベースから削除する際に、データベースに保存している予定とGoogleカレンダーから取得した予定の差分を取得したいと思いました。
そこで、Lodashを利用すると配列の差分を簡単に取得することができます。

準備

インストール

npmの場合

$ npm i -g npm
$ npm i --save lodash

yarnの場合

$ yarn add lodash

インポート

import _ from "lodash";

使い方

_.differenceWithの第一引数に対象の配列、第二引数に比較対象の配列、第三引数にコンパレーターを指定します。

console.log(dbEvents)
// →[ { id: "idOfEvent1"}, { id: "idOfEvent2"} ]

console.log(calendarEvents)
// →[ { id: "idOfEvent1" }, ]

const diff = _.differenceWith(dbEvents, calendarEvent, (objValue, othValue) => {
  // 第一引数のidと第二引数のidが一致した場合はtrueを返す
  if (objValue.id === othValue.id) {
    return true;
  }
});

console.log("Diff is", diff);
// → Diff is [ { id: "idOfEvent2" } ]



- Miyata Koki -
O:inc.でAmplify×React×React Nativeを使用して開発しています。大学のゼミでは統計学をPythonで行っています。
インターンやゼミで学んだ情報を発信していくので、フォロバするのでぜひこちらのアカウントのフォローお願いします!

1
2
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
1
2