我有两个对象数组:
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 属性不存在,那么它变为空):
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)
(其中 n
和m
分别是a
和b
的长度;你天真的解决方案
gave 将是 O(n*m)
,对 n
和 m
使用相同的含义。
关于javascript - 如何在 JavaScript 中对两个对象数组执行内部连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42429023/