I have an array of objects structured as follows:
pages= [
{
"id":1,
"name":"name1",
"languages":[
{
"id":1,
"lang":"en"
},
{
"id":2,
"lang":"de"
}
]
},
{
"id":2,
"name":"name2",
"languages":[
{
"id":1,
"lang":"en"
},
{
"id":2,
"lang":"de"
}
]
},
{
"id":3,
"name":"name3",
"languages":[
{
"id":1,
"lang":"en"
}
]
}
]
Furthermore, I have an array of selected languages (values are determined by clicking checkboxes):
selectedLanguages=['en'];
My goal is to filter the main array based on the values in selectedLanguages
. I've attempted the following code:
pages.filter(page => {
var present = false;
page.languages.map(l => {
if(selectedLanguages.includes(l.lang)) {
present = true;
}
});
if(present) {
return page;
}
})
The desired output is as follows: if selectedLanguages = ['en']
, then all items from pages
should be returned; if de
, then only the first 2 elements should be returned.
While this code works, I'm interested in improving its efficiency. Any suggestions would be greatly appreciated. Thank you!