javascript - 如何在 JavaScript 中对两个对象数组执行内部连接?

标签 javascript arrays inner-join

我有两个对象数组:

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

var b = [
  {id: 5, name: 'Mathew', position: '1'},
  {id: 6, name: 'Gracia', position: '2'},
  {id: 2, name: 'John', position: '2'},
  {id: 3, name: 'Matt', position: '2'},
]

我想对这两个数组 ab 进行内部连接,并像这样创建第三个数组(如果 position 属性不存在,那么它变为空):

var result = [{
  {id: 4, name: 'Greg', position: null},
  {id: 1, name: 'David', position: null},
  {id: 5, name: 'Mathew', position: '1'},
  {id: 6, name: 'Gracia', position: '2'},
  {id: 2, name: 'John', position: '2'},
  {id: 3, name: 'Matt', position: '2'},
}]

我的方法:

function innerJoinAB(a,b) {
    a.forEach(function(obj, index) {
        // Search through objects in first loop
        b.forEach(function(obj2,i2){
        // Find objects in 2nd loop
        // if obj1 is present in obj2 then push to result.
        });
    });
}

但是时间复杂度是O(N^2)。如何在 O(N) 中完成?我的 friend 告诉我,我们可以使用 reducer 和 Object.assign

我无法弄清楚这一点。请帮忙。

最佳答案

我不知道 reduce 在这里有什么帮助,但你可以使用 Map 来 在 O(n) 中完成相同的任务:

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

const b = [
  {id: 5, name: 'Mathew', position: '1'},
  {id: 6, name: 'Gracia', position: '2'},
  {id: 2, name: 'John', position: '2'},
  {id: 3, name: 'Matt', position: '2'}];

var m = new Map();
// Insert all entries keyed by ID into the Map, filling in placeholder
// 'position' since the Array 'a' lacks 'position' entirely:
a.forEach(function(x) { x.position = null; m.set(x.id, x); });

// For values in 'b', 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());

console.log(JSON.stringify(result));
.as-console-wrapper { max-height: 100% !important; top: 0; }

因为 Map 访问和更新是 O(1)(平均 - 因为散列 冲突和重新散列,它可以更长),这使得 O(n+m) (其中 nm分别是ab的长度;你天真的解决方案 gave 将是 O(n*m),对 nm 使用相同的含义。

关于javascript - 如何在 JavaScript 中对两个对象数组执行内部连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42429023/

相关文章:

javascript - JS : Array defined or undefined

python - 删除 numpy 数组的一列

c# - 在 C# 数组中添加和替换元素

mysql - 如何在一个查询中使用内连接获取列值的总和?

sql - 连接多个表返回重复项

mysql - 从 INNER JOIN 3 表中获取值以及每个表中的最新记录

javascript - 如何禁用 ng-repeat 行的点击?

javascript - 直接使用数组或将其分配给变量并使用它哪个更好?

Javascript 数组未填充

javascript - 如何使用Javascript从表中定位并删除一行?