【发布时间】:2017-07-14 17:13:45
【问题描述】:
我有两个对象数组:
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'},
]
我想对a 和b 这两个数组进行内连接,并像这样创建第三个数组(如果 position 属性不存在,则它变为 null):
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) 中做到这一点?我的朋友告诉我,我们可以使用减速器和Object.assign。
我无法弄清楚这一点。请帮忙。
【问题讨论】:
-
你有两个对象数组。似乎您需要将一个数组的所有值复制到一个新数组中,然后将第二个(以及后续)数组合并到其中。 Array.prototype.reduce 可能是一个好的开始。主键 id 是什么?由于您使用数组来保存对象,因此您可能还想创建一个 ID 到数组索引的索引,这样您就可以轻松找到 ID,而不必每次都遍历数组。
-
PS 内连接可能不是正确的术语,因为据我了解,这仅给出了两个集合都匹配的结果集(因此您的示例只会给出 ID 为 2 和 3 的行)。这更像是一个典型的合并。
-
@NicholasSmith 这是 JS,不是 JSON
-
根据您的输出示例,您想要的是完全外连接,而不是内连接。
标签: javascript arrays inner-join