searchFilteredData = [ { productId: 12345, carrierId: 3, //otherstuff }
{ productId: 28664, carrierId: 5, //otherstuff } ]
proposalProducts = [ 0: 12345, 1: 28664 ]
I have 2 arrays, one has a property productId
that can match items in the second array. How can I perform a loop to determine which items in searchFilteredData
have corresponding records in proposalProducts
?
CodePudding user response:
Just use filter
with includes
to check if element is in array:
searchFilteredData.filter(({ productId }) => proposalProducts.includes(productId))
searchFilteredData = [ { productId: 12345, carrierId: 3 },
{ productId: 28664, carrierId: 5 },
{ productId: 28232, carrierId: 5 }]
proposalProducts = [ 12345, 28664 ]
inProposalProducts = searchFilteredData.filter(({ productId }) => proposalProducts.includes(productId))
console.log(inProposalProducts)
CodePudding user response:
The common method is to create a new array with matching elements using Array.prototype.filter
let items = (searchFilteredData.filter(ele => proposalProducts.includes(ele.productId) )
If you want to loop through manually, use Array.prototype.forEach
or for-of
loop directly.
for (let item of searchFilteredData){
if (proposalProducts.includes(item))
console.log(item); //do something
}