I am trying to use Javascript to filter two array of object with different length, but resulted unsuccessful. Please help if you see this post 🙂
Two array of objects are as follow, notice the length of productList will always be larger or equals to shoppingCart.
I’d like to filter out the object with same size and color. I’m wondering if I need to loop through two array of objects before filtering.
First List- productList
let productList= [
{
"color_code": "DDFFBB",
"size": "S",
"stock": 3
},
{
"color_code": "DDFFBB",
"size": "M",
"stock": 5
},
{
"color_code": "CCCCCC",
"size": "S",
"stock": 4
},
{
"color_code": "CCCCCC",
"size": "M",
"stock": 1
},
{
"color_code": "BB7744",
"size": "S",
"stock": 2
},
{
"color_code": "BB7744",
"size": "M",
"stock": 6
}
]
Second list
let shoppingCart=[
{
"id": 201807202150,
"color": "DDFFBB",
"size": "M",
},
{
"id": 201807202150,
"color": "BB7744",
"size": "M",
},
{
"id": 201807202150,
"color": "DDFFBB",
"size": "S",
}
]
Expected output
{
"color_code": "DDFFBB",
"size": "S",
"stock": 3
},
{
"color_code": "DDFFBB",
"size": "M",
"stock": 5
},
{
"color_code": "BB7744",
"size": "M",
"stock": 6
}
Thanks for your help!!! You will save my day from infinite error.
>Solution :
You can use Array methods to filter the list.
We filter productList with a filter that checks to see whether there is some item in the shopping cart that matches it.
let productList= [
{
"color_code": "DDFFBB",
"size": "S",
"stock": 3
},
{
"color_code": "DDFFBB",
"size": "M",
"stock": 5
},
{
"color_code": "CCCCCC",
"size": "S",
"stock": 4
},
{
"color_code": "CCCCCC",
"size": "M",
"stock": 1
},
{
"color_code": "BB7744",
"size": "S",
"stock": 2
},
{
"color_code": "BB7744",
"size": "M",
"stock": 6
}
];
let shoppingCart=[
{
"id": 201807202150,
"color": "DDFFBB",
"size": "M",
},
{
"id": 201807202150,
"color": "BB7744",
"size": "M",
},
{
"id": 201807202150,
"color": "DDFFBB",
"size": "S",
}
]
const result = productList.filter(
(product) => shoppingCart.some(
(item) => item.color == product.color_code && item.size == product.size
)
);
console.log(result);