包含对象的 2 个数组的交集

jui*_*y89 0 javascript arrays

我使用下面的代码来交叉两个非常大的数组。由于目前需要很长时间,是否有可能提高其性能。

const arr1 = [  
    {  
       "number":"123",
       "firstName":"John",
       "lastName":"Smith",
       "email":"test1@test.com",
    },
    {  
       "number":"1234",
       "firstName":"Chad",
       "lastName":"Baker",
       "email":"test2@test.com",
    }
];
 
const arr2 = [  
    {  
        "number":"12345",
        "firstName":"Chad",
        "lastName":"Baker",
        "email":"test2@test.com",
    },
    {  
        "number":"123456",
        "firstName":"John",
        "lastName":"Smith",
        "email":"test1@test.com",
    }
]

 let arr3 = arr1.filter(a => arr2.some(b => { return a.firstName == b.firstName && a.lastName == b.lastName}));  
 
 console.log(arr3);
Run Code Online (Sandbox Code Playgroud)

der*_*her 5

id根据您的匹配标准创建一个并将其添加到Set您的一个数组的 a 中。然后你就有一个恒定的查找时间

let createId = (x) => `F:${x.firstName};L:${x.lastName}`;

//ids is a Set<string> which will only contain values created by the createId function
let ids = new Set(arr2.map(x => createId(x)));

//now in the filter, you have a set-lookup which is O(1) instead of 
//a linear search which is O(n)
let intersection = arr1.filter(x => ids.has(createId(x)));
Run Code Online (Sandbox Code Playgroud)

当然,你可以createId随意修改。通过在 的回调中调用它filter,您可以确保所有对象都得到相同的处理。