You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何高效计算两个对象数组的差异?

Optimal Solution to Find Differences Between Two Object Arrays

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:

  1. Create a Set of IDs from b2:
    We first extract all the id values from b2 and store them in a Set. This lets us check if an ID exists in b2 in constant time.

    const b2Ids = new Set(b2.map(item => item.id));
    
  2. Filter b1 to keep items not in b2:
    Use filter() on b1 to retain only those objects whose id isn't present in our b2Ids Set.

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:06:18