我有两个要比较的数组。如果两个数组中都存在一个特定的ID,则应该将该相关对象推入新数组中。
这是我的代码的当前状态
locations: Location[];
allImages: Images[];
specificImages: Images[]
locations.forEach((location) => {
allImages.forEach((img) => {
if(location.id === img.id) { // Here I want to check if a specific id occurs in both arrays
specificImages.push(img);
}
});
})
我目前正在使用Angular,如果在RxJS的CombineLatest运算符中进行了语句/查询,则使用Angular。如果将有一个不错的Typescript甚至RxJS解决方案,那就太好了。
答案 0 :(得分:2)
您可以使用filter
方法var intersect = list1.filter(a => list2.some(b => a.userId === b.userId));
list1 = [
{ id: 1, image: 'A' },
{ id: 2, image: 'B' },
{ id: 3, image: 'C' },
{ id: 4, image: 'D' },
{ id: 5, image: 'E' }
]
list2 = [
{ id: 1, image: 'A' },
{ id: 2, image: 'E' },
{ id: 6, image: 'C' }
]
var intersect = list1.filter(a => list2.some(b => a.id === b.id));
console.log(intersect)
答案 1 :(得分:1)
一种简单的方法是使用Array#some
some()方法测试数组中是否至少有一个元素 通过了由提供的功能实现的测试。
if (locations.some(l => l.id === img.id) && allImages.some(i => i.id === id)) {
specificImages.push(img)
}
您可以对此进行概括,以检查具有特定ID的对象是否包含在任意数量的数组中,即
const first = [...] const first = [...] 您可以对此进行概括,以检查具有特定ID的对象是否包含在任意数量的数组中,即
const first = [...]
const second = [...]
const third = [...]
const allArrays = [first, second, third]
if (allArrays.every(a => a.some(x => x.id === id)) {
// do your thing
}
答案 2 :(得分:1)
尝试使用Array的some
方法,也请先删除forEach:
allImages.forEach((img) => {
if(this.location.some(x => x.id === img.id)) {
// it returns true if Id found
specificImages.push(img);
}
});