I'm trying to solve a problem - need to return an array after entering a value to search. The depth of an array can be theoretically infinite. So I'm recursing to find suitable elements among any depth level and add them to the array and then return this array. But this code does not work as expected. I can't figure out what exactly I did wrong here.
const newList = [
{
role: "role111",
title: "title1",
},
{
role: "role222",
title: "title2",
},
{
role: "role333",
title: "title3",
},
{
role: "role444",
title: "title4",
items: [{
role: "role555",
title: "title5",
}, {
role: "role666",
title: "title6",
}, {
role: "role777",
title: "title7",
items: [{
role: "role888",
title: "title888",
},{
role: "role8888",
title: "title8888",
},]
},]
},
{
role: "role999",
title: "title999",
},
];
const text = "role888";
const testFunction = (
list,
text,
emptyArray
) => {
let arrayForRender = emptyArray;
return list?.filter((item) => {
if (item.title.toLowerCase().includes(text.toLowerCase())) {
arrayForRender = [...arrayForRender, item];
return arrayForRender;
}
if (item.items && item.items?.length > 0) {
testFunction(item.items, text, arrayForRender);
}
});
};
console.log(testFunction(newList, text, []));
P.S. I'm so sorry, but my question was originally formulated incorrectly and it is no longer relevant. But thanks to everyone who suggested and will tell you how to work with recursion correctly!
Via Active questions tagged javascript - Stack Overflow https://ift.tt/BeavPlI
Comments
Post a Comment