如何检查一个数组中的id是否出现在另一个数组中,然后将其推送到新数组

时间:2019-04-11 13:53:16

标签: javascript arrays angular typescript rxjs

我有两个要比较的数组。如果两个数组中都存在一个特定的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解决方案,那就太好了。

3 个答案:

答案 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);
    }
});