44
34

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.

2つの配列を比較して差分だけの配列を作る方法

Last updated at Posted at 2018-09-13

#手順

  • 差分を抜きたい配列Aに対してarray.filterをかけます
  • その中で別の比較対象の配列Bに対してindexOf(配列Aのitem) == -1してあげる

これで配列Aの要素かつ、配列Bに存在しない要素が残ります。🚀

パフォーマンス面でのベストプラクティスではないかもしれませんが、やり方の1つとして参考になればと思います👍

#コード

let arrayA = ["A", "B", "C", "D", "E"];
let arrayB = ["B", "D"];

// 配列Aに対して
let result = arrayA.filter(itemA => 
  // 配列Bに存在しない要素が返る
  arrayB.indexOf(itemA) == -1
);  
console.log(result); // [ 'A', 'C', 'E' ]
44
34
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
44
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?