I am writing a search function for this nested array but it is not working the way i want it work so the thing is if i am searching for Team 1B then i should get [{name: "Male 9 B", options: [{ label: "Team 1B", selected: false }] and i am also getting result but when i clear the input field i am not able to find other group name. i have mentioned the array and function which i have written
const groups = [
{
name: "Male 9 A",
options: [
{ label: "Team 1", selected: false },
{ label: "Team 2", selected: false },
{ label: "Team 3", selected: false },
{ label: "Team 4", selected: false },
{ label: "Team 5", selected: false }
]
},
{
name: "Male 9 B",
options: [
{ label: "Team 1B", selected: false },
{ label: "Team 2B", selected: false },
{ label: "Team 3B", selected: false },
{ label: "Team 4B", selected: false },
{ label: "Team 5B", selected: false },
]
}
];
let search = group.filter((group) => {
return group.options.find((player) =>
player.label.toLowerCase().includes(event.target.value.toLowerCase()))
})
.map((data) => ({
...data,
options: data.options.filter(player =>
player.label.toLowerCase().includes(event.target.value.toLowerCase()))
}));
console.log(search);
}
2
Answers
You will want to mix
Array.find
withArray.some
on your options.eg.
There is a typo You have used
group
instead ofgroups
in the filter function. The event object needs to be passed to the search function. Make sure you pass the event object to the function likesearchFunction(event)
Find the updated code below.The output will look like below