Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter nested array in object array by array of values

Considering below object array:

[
    {
        "guid": "j5Dc9Z",            
        "courses": [
            {
                "id": 1,
                "name": "foo",                    
            }
        ]
    },
    {
        "guid": "a5gdfS",
        "courses": [
            {
                "id": 2,
                "name": "bar",                    
            },
            {
                "id": 3,
                "name": "foo",                    
            },    
        ]
     },
     {
        "guid": "jHab6i",
        "courses": [
            {
                "id": 4,
                "name": "foobar",                    
            }   
        ]
     },  
     {...}    
]

I am trying to filter an object array, comparing IDs in the nested courses array with in the below array:

filter.courses = [1,3]

The following line works for the nth value in the array: (via https://stackoverflow.com/a/41347441/9766768)

let fil = filter(this.results, { courses: [{ id: this.filter.courses[n] }]});

However, I'm hoping to achieve this (pseudo code below):

let fil = filter(this.results, { courses: [{ id: this.filter.courses }]});

Expected output would be an array of objects containing any of the course IDs elements, in this case:

[
    {
        "guid": "j5Dc9Z",            
        "courses": [
            {
                "id": 1,
                "name": "foo",                    
            }
        ]
    },
    {
        "guid": "a5gdfS",
        "courses": [
            {
                "id": 2,
                "name": "bar",                    
            },
            {
                "id": 3,
                "name": "foo",                    
            },    
        ]
     }   
]

What would be considered the best solution in this case? Avoiding loops would be a bonus.

like image 502
Friso Hoekstra Avatar asked Aug 02 '18 09:08

Friso Hoekstra


People also ask

Can I filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

If you're trying to filter the elements whose course IDs contain in the filter.courses, you may use Array#every and Array#includes to do that:

const data = [{"guid":"j5Dc9Z","courses":[{"id":3,"name":"foo"}]},{"guid":"a5gdfS","courses":[{"id":1,"name":"bar"},{"id":3,"name":"foo"}]},{"guid":"jHab6i","courses":[{"id":7,"name":"foobar"}]}];
const courses = [1, 6, 3];

const r = data.filter(d => d.courses.every(c => courses.includes(c.id)));
console.log(r);
like image 64
31piy Avatar answered Sep 21 '22 16:09

31piy