javascript setの差分を取得する
- 作成日 2022.11.08
- 更新日 2022.12.15
- javascript
- javascript

javascriptで、setの差分を取得するサンプルコードを記述してます。「set」を配列化して「filter」で同じ値を条件に指定して生成します。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 108.0.5359.99
setの差分を取得
差分を取得するには
1. 「set」をスプレッド構文で配列に変更
2. 「filter」で双方の値が含まれているかを判定した結果を取得
3. 再度、配列化する
ことで可能です。
// 判定する関数
function getDiff(x, y) {
return new Set(
[...x].filter(function(v){return !y.has(v)})
);
}
const s1 = new Set(['a', 'b', 'c']);
const s2 = new Set(['a', 'b']);
const s3 = new Set(['a']);
const s4 = new Set([]);
let result = new Set([
...getDiff(s1, s2),...getDiff(s2, s1),
]);
console.log(result); // Set(1) {'c'}
result = new Set([
...getDiff(s1, s3),...getDiff(s3, s1),
]);
console.log(result); // Set(2) {'b', 'c'}
result = new Set([
...getDiff(s1, s4),...getDiff(s4, s1),
]);
console.log(result); // Set(3) {'a', 'b', 'c'}
実行結果

-
前の記事
GitHub Desktop 画面の拡大・縮小を行うショートカットキー 2022.11.08
-
次の記事
GAS エラー「Exception: Unexpected error while getting the method or property getFileById on object DriveApp.」が発生した場合の対処法 2022.11.08
コメントを書く