'How to search an array for matching property from another array?
I have a products array that looks like this:
const products =
[
{ product: 'prod_aaa', name: 'Starter' },
{ product: 'prod_bbb', name: 'Growth' },
{ product: 'prod_ccc', name: 'Elite' },
];
And a subscriptions array that looks something like this:
const subscriptions =
[
{
"status":"active",
"product": "prod_aaa",
"quantity": 1,
},
{
"status":"active",
"product": "prod_2342352345",
"quantity": 1,
}
];
Now I want to check the subscriptions array to find the first occurance of a matching product from the products array, and output the name of the product it finds (Starter/Growth/Elite).
I imagine it needs something like subscriptions.filter(). But I don't know how to make it give me the name of the product it finds.
I cannot change the subscriptions input, but I can change the plans input if needed.
What is the best way to do this?
P.S. My code is written in TypeScript
Solution 1:[1]
You mentioned filter(), but it should only be used when you are looking to use the array returned by it. Since you are only looking for the name, you would be better served with a for loop.
const products = [{
product: 'prod_aaa',
name: 'Starter'
},
{
product: 'prod_bbb',
name: 'Growth'
},
{
product: 'prod_ccc',
name: 'Elite'
},
];
const subscriptions = [{
"status": "active",
"product": "prod_aaa",
"quantity": 1,
},
{
"status": "active",
"product": "prod_2342352345",
"quantity": 1,
}
];
function find() {
for (const product of products) {
for (const subs of subscriptions) {
if (product.product === subs.product) {
return product.name;
}
}
}
}
console.log(find())
Edit: If you are absolutely looking for something with filter(). Here is what will help:
const products = [{
product: 'prod_aaa',
name: 'Starter'
},
{
product: 'prod_bbb',
name: 'Growth'
},
{
product: 'prod_ccc',
name: 'Elite'
},
];
const subscriptions = [{
"status": "active",
"product": "prod_aaa",
"quantity": 1,
},
{
"status": "active",
"product": "prod_2342352345",
"quantity": 1,
}
];
let result = products.filter(prod => {
return subscriptions.some(sub => prod.product === sub.product)
})[0].name;
console.log(result)
Solution 2:[2]
As opposed to Avneesh's approach I have traversed through the subscriptions array first.
// find a first subscription for which product is found in the products array.
let requiredSub = subscriptions.find(sub => products.some(p => p.product === sub.product))
let requiredProduct = requiredSub.product
Javascript Array.some method mdn reference -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
