Let's assume I have this array :
array = [{
name: 'my post',
categories: [{
slug: 'a-cat',
name: 'A Category'
}
},
{
name: 'my other post',
categories: [{
slug: 'another-category',
name: 'Another Category'
},
{
slug: 'a-cat',
name: 'A Category'
}
},
]
Now, I would like to filter it to get all element that contain the category another-category, this is what i've tried so far, but nothing ends up in the filteredArray
let filteredArray = array.filter(function (item) {
return item.categories.forEach(function(cat) {
return cat.slug === 'another-category'
})
})
Any thoughts on what I've done wrong ?
const array = [{
name: 'my post',
categories: [{
slug: 'a-cat',
name: 'A Category'
}]
},
{
name: 'my other post',
categories: [{
slug: 'another-category',
name: 'Another Category'
},
{
slug: 'a-cat',
name: 'A Category'
}
]
},
]
let filteredArray = array.filter(function(item) {
return item.categories.forEach(function(cat) {
return cat.slug === 'another-category'
})
})
console.log(filteredArray)
forEachreturnsundefinedwhich is treated asfalseinfilter. What is your desired result?