首頁 >web前端 >js教程 >如何有效地找到兩個 JavaScript 物件陣列之間的差異?

如何有效地找到兩個 JavaScript 物件陣列之間的差異?

Linda Hamilton
Linda Hamilton原創
2024-12-13 14:35:10910瀏覽

How Can I Efficiently Find the Differences Between Two JavaScript Arrays of Objects?

在 JavaScript 中擷取數組差異

給定兩個物件數組,需要識別它們的差異。在這方面,以下程式碼片段提供了一個解決方案:

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn