Typescript:使用Lambda函数从两个数组中查找公共对象 [英] Typescript : Find common objects from two array using Lambda function
本文介绍了Typescript:使用Lambda函数从两个数组中查找公共对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Typescript解决以下问题.我想在列表中搜索对象而不是简单的字母或数字.
I am using Typescript for below problem. I want to search object not simple alphabetic or number in the list.
下面是两个数组.我想在不使用任何第三方库的情况下,在单独的列表中获取常用对象.
Below are the two arrays. I want to get common objects in separate list without using any third party library.
firstArray = [
{
"id": 4,
"name": "Tata"
},
{
"id": 11,
"name": "Maruti"
},
{
"id": 14,
"name": "Mahindra"
}
]
secondArray = [
{
"id": 4,
"name": "Tata"
},
{
"id": 11,
"name": "Maruti"
},
{
"id": 15,
"name": "Hyundai"
},
{
"id": 21,
"name": "Honda"
}
]
// Get Common Elements
// I am getting blank array as output
console.log(firstArray.filter(( make ) => secondArray.includes( make)));
有什么功能或方法可以找到commons元素吗?
Is there good function or way to find out commons element?
推荐答案
您可以将 array#filter
与 array#some
一起使用.对于第一个数组中的每个对象,检查另一个数组中是否存在 id
和 name
.
You can use array#filter
with array#some
. For each object in the first array, check if id
and name
exist in the other array.
const firstArray = [{ "id": 4, "name": "Tata" }, { "id": 11, "name": "Maruti" }, { "id": 14, "name": "Mahindra" } ],
secondArray = [{ "id": 4, "name": "Tata" }, { "id": 11, "name": "Maruti" }, { "id": 15, "name": "Hyundai" }, { "id": 21, "name": "Honda" } ],
result = firstArray.filter(o => secondArray.some(({id,name}) => o.id === id && o.name === name));
console.log(result);
这篇关于Typescript:使用Lambda函数从两个数组中查找公共对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文