0

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)

3
  • Try to explain what your script does and you might get an idea why it doesn't work as expected. Why fieldIds.map(...) Why course.fields.map(...)? Commented Sep 10, 2020 at 13:50
  • Does this answer your question? Filtering array based on nested property Commented Sep 10, 2020 at 13:56
  • No, it does not, see my edits Commented Sep 10, 2020 at 14:13

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.