0
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.

1
  • Make an array of all the IDs in otherProducts. Then filter customerProducts using a callback function that uses otherIds.includes(product.id) Commented Oct 1, 2020 at 4:30

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.