JSFiddle - React, Tailwind, and code Playground
by jun68ykt
HTML
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
<html><body>
This is a sample code for
<a href="https://teratail.com/questions/128121">Teratail question No.128121</a>.
</body></html>
JavaScript
//配列 ar1、 ar2の差分を、[ 差集合(ar2-ar1)の配列, 差集合(ar1-ar2)の配列 ] という配列として返す関数
const diff = (ar1, ar2) => [[ar2,ar1], [ar1,ar2]].map(e => _.difference(...e));
// あらかじめ定義された配列
const initialArray = ['a', 'b', 'c']; // 初期配列
// 更新後の配列(4パターン)
const updatedArray1 = ['a', 'c']; // 削除
const updatedArray2 = ['a', 'b', 'c', 'd']; // 追加
const updatedArray3 = ['b', 'd']; // 削除 & 追加
const updatedArray4 = []; // 全削除
[
updatedArray1,
updatedArray2,
updatedArray3,
updatedArray4
].forEach(ary => {
console.log(`元の配列:${initialArray} => 更新後:${ary}`);
console.log(diff(initialArray, ary));
});