timmyLtus
timmyLtus

Reputation: 274

Filtering array of objects against another array of objects?

customerProducts: [
  {
    name: "foo",
    id: 123
  },
  {
    name: "test",
    id: 44
  }
]

otherProducts: [
  {
    name: "other",
    id: 44
  },
  {
    name: "test",
    id: 21
  }
]

I want to iterate through customerProducts, which is an array of objects. I want to filter the customerProducts that have an ID that another array of objects, otherProducts, has. So for examople, I'd want the returned result in this case to be:

  {
    name: "test",
    id: 44
  }

since otherProducts has an id of 44.

I was thinking of mapping through otherProducts and just returning an array of IDs, then running a forEach on that but that seems like a long way of doing it.

Upvotes: 0

Views: 156

Answers (3)

Azad
Azad

Reputation: 5264

declare customerProducts , otherProducts as JS array variable and use JS Array filter find functions

let customerProducts = [
  {
    name: "foo",
    id: 123
  },
  {
    name: "test",
    id: 44
  }
]

let otherProducts = [
  {
    name: "other",
    id: 44
  },
  {
    name: "test",
    id: 21
  }
];

let filtered = customerProducts.filter( el => otherProducts.find( e => e.id == el.id) )

console.log(filtered);

Upvotes: 0

ihimv
ihimv

Reputation: 1474

This can be done by using array methods filter and some.

customerProducts.filter((x)=> otherProducts.some(y=> y.id === x.id));

Explanation: filter method will call each and every element in the otherProducts array and check if the id of customerProduct is present in otherProducts for at least one element.

Upvotes: 0

Phil
Phil

Reputation: 164813

Create an indexed Set of the values to filter by (id from otherProducts) then filter customerProducts by that Set

const customerProducts = [{name: "foo",id: 123},{name: "test",id: 44}]

const otherProducts = [{name: "other",id: 44},{name: "test",id: 21}]

const otherProductIds = new Set(otherProducts.map(({ id }) => id))

const filteredCustomerProducts = customerProducts.filter(({ id }) => 
  otherProductIds.has(id))
  
console.info(filteredCustomerProducts)

Upvotes: 3

Related Questions