JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/gh/eu81273/jsfiddle-console/console.js"></script>
JavaScript
const getDiffFrom2Arrays = (oldValues, newValues) => {
const inputObjects = [
{ name: "oldValues", value: oldValues },
{ name: "newValues", value: newValues },
];
const object = inputObjects.reduce(
(o1, { name, value }) =>
Object.assign(o1, {
[name]: value.reduce(
(o2, f) => Object.assign(o2, { [f]: o2[f] ? o2[f] + 1 : 1 }),
{}
),
}),
{}
);
const diff1 = Object.entries(object.newValues).reduce(
(o, [k, v]) => {
if (object.oldValues[k]) {
const d = v - object.oldValues[k];
o.changed.push({ [k]: ((d < 0 || d == 0 ? "" : "+") + d).toString() });
} else {
o.addedNewValues.push({ [k]: v });
}
return o;
},
{ addedNewValues: [], changed: [] }
);
const diff2 = Object.entries(object.oldValues).reduce(
(o, [k, v]) => {
if (!object.newValues[k]) o.removed.push({ [k]: v });
return o;
},
{ removed: [] }
);
return Object.assign(diff1, diff2);
};
const oldValues = ["a1", "b1", "b1", "c1", "d1", "e1"];
const newValues = ["a1", "b1", "d1", "a1", "d1", "f1", "g1", "a1", "g1"];
const res = getDiffFrom2Arrays(oldValues, newValues);
console.log(res);