1

I have two arrays that I want to compare. If a specific id occurs in both arrays, then that related object should be pushed into a new array.

Here is the current state of my code

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

I am currently working with Angular and this if statment/query is taking place within the combineLatest operator of RxJS. Would be great if there would be a nice Typescript or even RxJS solution for this.

Codehan25
  • 2,704
  • 10
  • 47
  • 94

3 Answers3

2

You can do like this using filter method 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)
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
1

An easy way to do it is with Array#some

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

if (locations.some(l => l.id === img.id) && allImages.some(i => i.id === id)) {
  specificImages.push(img)
}

You can generalise this to check whether an object with a specific id is included in an arbitrary number of arrays, I.e.

const first = [...] const first = [...] You can generalise this to check whether an object with a specific id is included in an arbitrary number of arrays, I.e.

const first = [...]
const second = [...]
const third = [...]
const allArrays = [first, second, third]

if (allArrays.every(a => a.some(x => x.id === id)) {
  // do your thing
}
bugs
  • 14,631
  • 5
  • 48
  • 52
1

Try with Array's some method, also remove first forEach:

allImages.forEach((img) => {
    if(this.location.some(x => x.id === img.id)) { 
      // it returns true if Id found
      specificImages.push(img);
    }
});
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84