给定两个对象数组,需要识别它们的差异。在这方面,以下代码片段提供了一个解决方案:
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);
此代码使用提供的比较函数 (isSameUser) 有效地比较对象数组,并识别每个数组中的唯一元素。最终结果是一个包含两个输入数组中这些唯一元素的数组。
以上是如何有效地查找两个 JavaScript 对象数组之间的差异?的详细内容。更多信息请关注PHP中文网其他相关文章!