JavaScript中如何高效计算两个对象数组的差异?
First, let's go with the most efficient approach here—using a Set for O(1) lookups, which keeps the overall time complexity at O(n + m) (where n is the length of b1 and m is the length of b2). This is way faster than nested checks, especially as your arrays grow larger.
Step-by-Step Implementation:
Create a Set of IDs from
b2:
We first extract all theidvalues fromb2and store them in a Set. This lets us check if an ID exists inb2in constant time.const b2Ids = new Set(b2.map(item => item.id));Filter
b1to keep items not inb2:
Usefilter()onb1to retain only those objects whoseidisn't present in ourb2IdsSet.var b1 = [ { id: 0, name: 'john' }, { id: 1, name: 'mary' }, { id: 2, name: 'pablo' }, { id: 3, name: 'escobar' } ]; var b2 = [ { id: 0, name: 'john' }, { id: 1, name: 'mary' } ]; const b2Ids = new Set(b2.map(item => item.id)); const difference = b1.filter(item => !b2Ids.has(item.id)); console.log(difference); // Output: [{ id: 2, name: 'pablo' }, { id: 3, name: 'escobar' }]
Why Your Filter + Reduce Approach Might Have Failed:
If you were using something like b1.filter(item => !b2.reduce((match, curr) => match || curr.id === item.id, false)), this would technically work but is inefficient (O(n*m) time complexity). However, if it wasn't returning the right result, you might have had a logic error in your reduce callback—like not properly accumulating the match status, or comparing the wrong properties.
The Set-based approach is not only faster but also more readable and less prone to such errors.
内容的提问来源于stack exchange,提问作者RobotMan

