Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter an array based on the values of one of its nested arrays?

Say I have an array of objects that follows the pattern below:

var posts = [
    {
        title: post_ab,
        category_array : [
            { id: 1, slug: category-a },
            { id: 2, slug: category-b }
        ]
    },
    {
        title: post_ac,
        category_array : [
            { id: 1, slug: category-a },
            { id: 3, slug: category-c }
        ]
    },
    {
        title: post_bc,
        category_array : [
            { id: 2, slug: category-b },
            { id: 3, slug: category-c }
        ]
    }
]

I'm trying to filter the above array, and only return values where the category_array contains a slug matching a specified value.

For example, if I wanted to filter against 'category-c', only the 2nd and 3rd values (post_ac and post_bc) would be returned.

I've tried with nested filters, which is getting me nowhere:

var currentCategory = 'category-b';

var filteredPosts = function( posts ) {
    return posts.filter( function( post ){
        return post.category_array.filter( function( category ){
            return category.slug === currentCategory;
        })
    })
}
like image 848
verism Avatar asked Dec 28 '25 05:12

verism


1 Answers

You have to use Array.prototype.some() in the inner loop:

var filteredPosts = function(posts) {
    return posts.filter(function(post){
        return post["category_array"].some(function(category){
            return category.slug === currentCategory;
        });
    });
}

It will return a boolean result that can be used in the .filter() callback.

like image 112
cнŝdk Avatar answered Dec 31 '25 00:12

cнŝdk