2👍
✅
You can use .every()
for that.
Here is an example:
checked = [
'orange', 'apple', 'juice'
]
products = [{
title: 'this is product title',
categories: [
'apple', 'juice'
]
}];
const filteredProducts = products.filter(({ categories }) => categories.every(cat => checked.includes(cat)));
console.log(filteredProducts);
This will return an array of products that have a categories
array with all its values included in the checked
array.
I’m not sure if this is exactly what you’re trying to do, if you instead want to get all the products with a categories
array that has at least one of its values in the checked
array, use .some()
instead of .every()
.
2👍
You’re trying to check if an array of strings includes an array (which won’t work even if your initial array contained arrays). Instead of using .includes()
, use .every()
on product.categories
to check if all items within this array are contained within checked:
const checked = ['orange', 'apple', 'juice'];
const products = [
{
title: 'this is product title',
categories: ['apple', 'juice']
}
];
const computed = products.filter(product => product.categories.every(item => checked.includes(item) || !checked.length));
console.log(computed);
Source:stackexchange.com