LoginSignup
9
4

More than 5 years have passed since last update.

JavaScriptで2つのオブジェクトの配列を比較する

Last updated at Posted at 2017-10-18

下記のように2つのオブジェクトの配列について、xyが同じ値のとき、dataの値を比較して、異なっていたら差分箇所を出力するとした際にArray.prototype.filterを使ってフィルタリングしたのでメモ。

data.js
  const arr1 = [
    {
      x: 1,
      y: 1,
      data: a
    },
    {
      x: 1,
      y: 2,
      data: b
    },
    {
      x: 1,
      y: 3,
      data: c
    },
  ];

  const arr2 = [
    {
      x: 1,
      y: 1,
      data: a
    },
    {
      x: 1,
      y: 2,
      data: b
    },
    {
      x: 1,
      y: 3,
      data: d
    },
  ];
filter.js
  const diff = arr1.filter(item1 => {
    const notMatch = arr2.filter(
      item2 =>
        item1 x === item2.x &&
        item1.y === item2.y &&
        item1.data !== item2.data
    });
    return notMatch.length !== 0;
  });

  if (diff.length !== 0) {
    console.info('Different!!!');
  }

追記、コメントでsomeのほうがいいだろという指摘があったので追記

some.js
  const diff = arr1.some(item1 => {
    arr2.some(
      item2 =>
        item1 x === item2.x &&
        item1.y === item2.y &&
        item1.data !== item2.data
    });
  });

  if (diff) {
    console.info('Different!!!');
  }

ただ、判定するだけならsomeのほうがわかりやすいですね。

かなり特殊な状況ですが、思いつくまでに時間かかったのでQiitaにて供養。

9
4
2

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
9
4