給定兩個物件數組,需要識別它們的差異。在這方面,以下程式碼片段提供了一個解決方案:
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中文網其他相關文章!