Reputation:
I was wondering how I can check this. Example:
var products = [
{
title: 'Product 1',
categories: ['One', 'Two', 'Three']
},
{
title: 'Product 2',
categories: ['Three', 'Four']
}
];
var categories = ['Two','Four'];
How can I get the two products matching one of the categories? Hope someone can help me out :)
Upvotes: 0
Views: 140
Reputation: 6992
Using simple for
:
var products = [
{
title: 'Product 1',
categories: ['One', 'Two', 'Three']
},
{
title: 'Product 2',
categories: ['Three', 'Four']
}
];
var categories = ['Two', 'Four'];
var list = []
for (x in products) {
for (y in products[x].categories) {
if (categories.indexOf(products[x].categories[y]) != -1) {
list.push(products[x].title)
}
}
}
console.log(list) //here your match
Upvotes: 0
Reputation: 275
Just simple looping through:
var foundproducts = [];
for (i = 0; i < products.length; i++) {
for (u = 0; u < categories.length; u++) {
if (products[i].categories.indexOf(categories[u]) != -1) {
foundproducts.push(products[i].title);
break;
}
}
}
Upvotes: 0
Reputation: 47968
products.filter(function(product) {
return categories.some(function(cat) {
return product.categories.indexOf(cat) >= 0;
});
});
_.filter(products, function(product) {
return _.some(categories, function(cat) {
return _.indexOf(product.categories, cat) >= 0;
});
});
Upvotes: 6
Reputation: 6235
Not very good solution from code side but it can be clear (if someone don't understand) and it's works
var products = [
{
title: 'Product 1',
categories: ['One', 'Two', 'Three']
},
{
title: 'Product 2',
categories: ['Three', 'Four']
}
];
var categories = ['Two','Four'];
var retArr = [];
for (i = 0; i < categories.length; ++i) {
for (j = 0; j < products.length; ++j) {
if(products[j].categories.indexOf(categories[i]) > -1){ // check if product categories contains some category. If yes, then add to array
retArr.push(products[j]);
}
}
}
console.log(retArr);
Upvotes: 0