Home >Web Front-end >JS Tutorial >How Can I Efficiently Find the Differences Between Two JavaScript Arrays of Objects?
Given two arrays of objects, it's desirable to identify their dissimilarities. In this regard, the following code snippet offers a solution:
const a = [{ value: "0", display: "Jamsheer" }, { value: "1", display: "Muhammed" }, { value: "2", display: "Ravi" }, { value: "3", display: "Ajmal" }, { value: "4", display: "Ryan" }]; const b = [{ value: "0", display: "Jamsheer" }, { value: "1", display: "Muhammed" }, { value: "2", display: "Ravi" }, { value: "3", display: "Ajmal" }]; // Equality comparison function const isSameUser = (a, b) => a.value === b.value && a.display === b.display; // Filter function to identify unique elements in the left array (a) const onlyInLeft = (left, right, compareFunction) => left.filter(leftValue => !right.some(rightValue => compareFunction(leftValue, rightValue) ) ); // Apply the filter functions const onlyInA = onlyInLeft(a, b, isSameUser); const onlyInB = onlyInLeft(b, a, isSameUser); // Concatenate the unique elements from both arrays const result = [...onlyInA, ...onlyInB]; console.log(result);
This code effectively compares the arrays of objects using the provided comparison function (isSameUser) and identifies the unique elements in each array. The final result is an array containing these unique elements from both input arrays.
The above is the detailed content of How Can I Efficiently Find the Differences Between Two JavaScript Arrays of Objects?. For more information, please follow other related articles on the PHP Chinese website!