我有一个简单的数字数组(对于我的应用程序,它代表用户ID)。例如...
[1, 2, 3]
我还有一个对象数组,例如
[
{Id: 1, FirstName: "Bob", LastName: "Jones", EmailAddress: "bob@bob.com"},
{Id: 2, FirstName: "Tessa", LastName: "Wong", EmailAddress: "tes@wong.com"},
{Id: 3, FirstName: "Craig", LastName: "Murray", EmailAddress: "Craig@muz.com"},
{Id: 4, FirstName: "Bryce", LastName: "Willamson", EmailAddress: "email@me.com"},
{Id: 5, FirstName: "Tony", LastName: "Ocka", EmailAddress: "toni@oz.com"}
]
我需要做的是用第二个对象数组中的键Id
匹配出现在初始数组中的所有值(并返回一个仅包含匹配项的新对象完整数组)。例如,在这种情况下,我要寻找的结果是:
[
{Id: 1, FirstName: "Bob", LastName: "Jones", EmailAddress: "bob@bob.com"},
{Id: 2, FirstName: "Tessa", LastName: "Wong", EmailAddress: "tes@wong.com"},
{Id: 3, FirstName: "Craig", LastName: "Murray", EmailAddress: "Craig@muz.com"},
]
任何帮助将不胜感激。
答案 0 :(得分:3)
在OP中显示您的尝试总是很有帮助的,以帮助其他用户了解您的处境。
您可以为此使用“ Array.filter”和“ includes”。
let arr1 = [1,2,3]
let arr2 = [
{Id: 1, FirstName: "Bob", LastName: "Jones", EmailAddress: "bob@bob.com"},
{Id: 2, FirstName: "Tessa", LastName: "Wong", EmailAddress: "tes@wong.com"},
{Id: 3, FirstName: "Craig", LastName: "Murray", EmailAddress: "Craig@muz.com"},
{Id: 4, FirstName: "Bryce", LastName: "Willamson", EmailAddress: "email@me.com"},
{Id: 5, FirstName: "Tony", LastName: "Ocka", EmailAddress: "toni@oz.com"}
]
let result = arr2.filter(d => arr1.includes(d.Id))
console.log(result)
答案 1 :(得分:0)
您也可以通过遍历第二个数组来实现此目的
let arr1 = [1,2,3];
let arr2 = [
{Id: 1, FirstName: "Bob", LastName: "Jones", EmailAddress: "bob@bob.com"},
{Id: 2, FirstName: "Tessa", LastName: "Wong", EmailAddress: "tes@wong.com"},
{Id: 3, FirstName: "Craig", LastName: "Murray", EmailAddress: "Craig@muz.com"},
{Id: 4, FirstName: "Bryce", LastName: "Willamson", EmailAddress: "email@me.com"},
{Id: 5, FirstName: "Tony", LastName: "Ocka", EmailAddress: "toni@oz.com"}
]
let result = [];
for(let i in arr2) {
if(arr1.indexOf(arr2[i].Id)!==-1) result.push(arr2[i]);
}
console.log(result);
答案 2 :(得分:0)
您可以使用Set
来优化性能。数组的查找操作花费O(n)
,这将使函数的整体时间复杂度增加到O(n ^ 2),而Set
中的查找操作花费了O(1)
,因此整体时间复杂度为O( n)。
let arr1 = [1,2,3]
let set = new Set(arr1);
let arr2 = [ {Id: 1, FirstName: "Bob", LastName: "Jones", EmailAddress: "bob@bob.com"}, {Id: 2, FirstName: "Tessa", LastName: "Wong", EmailAddress: "tes@wong.com"}, {Id: 3, FirstName: "Craig", LastName: "Murray", EmailAddress: "Craig@muz.com"}, {Id: 4, FirstName: "Bryce", LastName: "Willamson", EmailAddress: "email@me.com"}, {Id: 5, FirstName: "Tony", LastName: "Ocka", EmailAddress: "toni@oz.com"}];
let result = arr2.filter(({Id}) => set.has(Id))
console.log(result)