我有两个对象数组:
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
进行内部连接,并创建第三个这样的数组(如果位置属性不存在,则它变为空):
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
。
我无法弄清楚这一点。请帮忙。
原文由 TechnoCorner 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何解决它的方法之一。