如何获取两个对象数组的差异并返回新数组?
Solution: Get Difference Elements Between Two Object Arrays
Alright, let's solve this problem where we need to find all elements that exist in either of the two object arrays but not in both. We'll use the _id property as the primary unique identifier, and also handle cases where elements don't have an _id.
Step-by-Step Approach
The core idea is straightforward:
- Find all elements in the original (
NATIVE) array that aren't present in the updated (NEW) array - Find all elements in the updated (
NEW) array that aren't present in the original (NATIVE) array - Combine these two sets of elements into a single result array
First, let's create a helper function to check if an element exists in an array. This function will prioritize matching by _id (since that's the unique key in your example), and fall back to comparing the entire object if _id isn't present.
Code Implementation
// Helper function to check if an element exists in a target array function isElementPresent(element, targetArray) { // Prioritize matching by _id if the element has one if (element._id) { return targetArray.some(item => item._id === element._id); } // For elements without _id, compare the full object (works for simple objects) const elementStr = JSON.stringify(element); return targetArray.some(item => JSON.stringify(item) === elementStr); } // Main function to retrieve difference elements function getArrayDifferences(nativeArray, newArray) { // Filter elements that only exist in the native array const onlyInNative = nativeArray.filter(element => !isElementPresent(element, newArray)); // Filter elements that only exist in the new array const onlyInNew = newArray.filter(element => !isElementPresent(element, nativeArray)); // Combine and return the result return [...onlyInNative, ...onlyInNew]; } // Test with your example data const NATIVE = [{"_id": "asd12312312", "name": "item 01"}, {"_id": "1123rwerwe", "name": "item 02"}]; const NEW = [{"_id": "1123rwerwe", "name": "item 02"}, {"name": "item 03"}]; console.log(getArrayDifferences(NATIVE, NEW)); // Output: [{"_id": "asd12312312", "name": "item 01"}, {"name": "item 03"}]
Key Notes
_idPriority: The helper function first checks for_idmatches, which aligns with your example where_idacts as the unique identifier.- No
_idHandling: For elements without an_id, we useJSON.stringifyto compare the entire object. This works great for simple objects like your example, but if you're dealing with complex nested objects or objects with functions, you'll need a custom deep equality check instead. - Edge Cases: This function handles empty arrays, duplicate elements within a single array, and mixed elements with/without
_idwithout issues.
内容的提问来源于stack exchange,提问作者Renan Rodrigues
相关产品推荐
相关产品推荐

