Ilyas Ghomrani
Ilyas Ghomrani

Reputation: 479

Filter array of objects based on value of an inside array

I want to select from array courses only the courses that have at least one field with id in fieldIds array. bellow is the format of thw arrays:

courses = [
    {id: 5, name:"some name1", fields:[{id: 28, name:"field name"}, {id: 29, name:"field name2"}]},
    {id: 18, name:"some name2", fields:[{id: 11, name:"field name"}, {id: 28, name:"field name2"}]},
    {id: 7, name:"some name3", fields:[{id: 29, name:"field name"}, {id: 9, name:"field name2"}]}
]

fieldIds = [29, 9]

So the result should be:

courses = [
    {id: 5, name:"some name1", fields:[{id: 28, name:"field name"}, {id: 29, name:"field name2"}]},
    {id: 7, name:"some name3", fields:[{id: 29, name:"field name"}, {id: 9, name:"field name2"}]}
]

This is what I tried and I always got the same array it changes nothing

fieldIds.map(fieldId => {
    courses = courses.filter(course => course.fields.map(f => f.id == fieldId);
});

EDIT after trying the response of this question as follow:

fieldIds.map(fieldId => {
    courses = courses.filter(course => course.fields.some(f => f.id == fielded))
}

if the fieldIds contain a couple of IDs for example the function returns courses belong to all fields. (and I want to extract the courses that have at least one of the selected fields)

Upvotes: 0

Views: 196

Answers (1)

Carlo Corradini
Carlo Corradini

Reputation: 3425

Here is the working solution:

const courses = [
    {id: 5, name:"some name1", fields:[{id: 28, name:"field name"}, {id: 29, name:"field name2"}]},
    {id: 18, name:"some name2", fields:[{id: 11, name:"field name"}, {id: 28, name:"field name2"}]},
    {id: 7, name:"some name3", fields:[{id: 29, name:"field name"}, {id: 9, name:"field name2"}]}
];

const fieldIds = [29, 9];

const filtered_courses = courses.filter(course => course.fields.some(field => fieldIds.includes(field.id)));

console.log(filtered_courses);

Filter the courses array with the condition (some) verifying that at least one element in the fields array has an equal value from fieldIds array.

PS: If fields array(s) and fieldIds array are sorted in ASC or DESC order the "algorithm" is much faster since the some method return earlier.

Upvotes: 2

Related Questions