How can I perform an inner join with two object arrays in JavaScript?

后端 未结 7 2008
闹比i
闹比i 2020-12-10 13:56

I have two object arrays:

var a = [
  {id: 4, name: \'Greg\'},
  {id: 1, name: \'David\'},
  {id: 2, name: \'John\'},
  {id: 3, name: \'Matt\'},
]

var b = [         


        
7条回答
  •  甜味超标
    2020-12-10 14:45

    I don't know how reduce would help here, but you could use a Map to accomplish the same task in O(n):

    var m = new Map();
    // Insert all entries keyed by ID into map, filling in placeholder position
    // since a lacks position entirely
    a.forEach(function(x) { x.position = null; m.set(x.id, x); });
    
    // For b values, insert them if missing, otherwise, update existing values
    b.forEach(function(x) {
        var existing = m.get(x.id);
        if (existing === undefined)
            m.set(x.id, x);
        else
            Object.assign(existing, x);    
    });
    
    // Extract resulting combined objects from the Map as an Array
    var result = Array.from(m.values());
    

    Because Map access and updates are O(1) (average case, thanks to hash collisions and rehashing, it can be longer), this makes O(n+m) (where n and m are the lengths of a and b respectively; the naive solution you gave would be O(n*m) using the same meaning for n and m).

提交回复
热议问题