I want to filter the below array:
let data = [
{
title : "fashion",
options : [{
title : "men",
options : [
{ title : "shirt"},
{ title : "pants"},
{ title : "belt"},
{ title : "shoes"},
]
},{
title : "women",
options : [
{ title : "shirt"},
{ title : "jeans"},
{ title : "sarees"},
{ title : "salwar"},
]
}
]
},
{
title : "electronics",
options : [{
title : "mobile",
options : [
{ title : "Samsung"},
{ title : "Nokia"},
{ title : "Apple"},
{ title : "OnePlus"},
]
},{
title : "TV",
options : [
{ title : "Samsung"},
{ title : "Sony"},
{ title : "Sansui"},
{ title : "OnePlus"},
]
}
]
}
]
I want to filter the options array in the seond level nesting. For example, I want to filter and find out the Samsung options alone and get the below output:
let data = [
{
title : "electronics",
options : [{
title : "mobile",
options : [
{ title : "Samsung"}
]
},{
title : "TV",
options : [
{ title : "Samsung"},
]
}
]
}
]
I am able to achieve the same using three nested for loop. Is there a better way to do this using filter and map?
3
Answers
You can use the following approach, it uses the map and the filter function to filter the array.
Let me know if this solves your problem
To achieve a good performance you 2 nested
Array::reduce()
to avoid intermediate arrays:This should do the job