The search functionality requirement is such that when the search input matches with the categories.name or inside categories -> dishes -> dish.name the output should be the categories.name.
Below is the JS data -
[
{
name: "Tikka",
img: "paneer malai tikka.jpg",
categories: [
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745b6",
name: "Tikka",
dishes: [
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745b7",
name: "paneer malai tikka",
img: "paneer malai tikka.jpg",
type: "veg", },
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745b9",
name: "panner jaitoni tikka",
img: "jaitooni paneer tikka.png",
type: "veg",
},
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745bb",
name: "chicken pahadi tikka",
img: "chicken pahadi tikka.jpeg",
type: "non veg",
},
],
},
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745f2",
name: "Tikka",
dishes: [
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745f3",
name: "lehsuni fish tikka",
img: "lehsuni fish tikka.jpg",
type: "non veg",
},
],
},
],
},
];
FilterSearch.js
However below function is returning output with duplicate output.
let filteredData = [];
categories.forEach((category) =>
category.categories.forEach((subcategory) =>
subcategory.dishes.forEach(dish => {
if (dish.name.toLowerCase().includes(searchInput)) {
filteredData.push(category);
};
}
)
)
)
Any help would be greatly appreciated. Please let me know if you need more information regarding this.
Why not just prevent duplications in the first place by checking if already exists?
var categories = [{
name: "Tikka",
img: "paneer malai tikka.jpg",
categories: [{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745b6",
name: "Tikka",
dishes: [{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745b7",
name: "paneer malai tikka",
img: "paneer malai tikka.jpg",
type: "veg",
},
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745b9",
name: "panner jaitoni tikka",
img: "jaitooni paneer tikka.png",
type: "veg",
},
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745bb",
name: "chicken pahadi tikka",
img: "chicken pahadi tikka.jpeg",
type: "non veg",
},
],
},
{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745f2",
name: "Tikka",
dishes: [{
isActive: true,
isDeleted: false,
_id: "61a22648521aa07d718745f3",
name: "lehsuni fish tikka",
img: "lehsuni fish tikka.jpg",
type: "non veg",
}, ],
},
],
}, ];
let filteredData = [];
var searchInput = "a"
categories.forEach((category) =>
category.categories.forEach((subcategory) =>
subcategory.dishes.forEach(dish => {
if (dish.name.toLowerCase().includes(searchInput)) {
if (filteredData.indexOf(category)==-1) {
filteredData.push(category);
}
};
})
)
)
console.log(filteredData)
.as-console-wrapper {max-height: 100% !important}