I am trying to write a recursive function in javascript but not work properly. i have a json array of objects data where i want to find something based on key then find again based on gotopage key in search object.
like : find orange -> gotopage -> orange_store ->find -> orange_store -> gotopage -> yellow_store -> find so the same process goes in recursively.can you please help where i'm going wrong in my approach.
[
{
"id": 1,
"find": "orange",
"gotopage": "orange_store"
},
{
"id": 2,
"find": "orange_store",
"gotopage": "yellow_store"
},
{
"id": 3,
"find": "black_store",
"gotopage": "black_store"
},
{
"id": 4,
"find": "yellow_store",
"gotopage": "white_store"
},
{
"id": 5,
"find": "black_store",
"gotopage": "red_store"
}
]
function searchRec(search, myArray) {
for (var i = 0; i < myArray.length; i++) {
var res = [];
if (myArray[i].find == search) {
if (myArray[i] !== null) {
console.log(myArray[i]);
res = searchRec(myArray[i].gotopage, myArray);
if (res !== null) {
return res;
}
return myArray[i];
}
}
}
}
function findNode(arr) {
for (i = 0; i < arr.length; i++) {
searchRec(arr[i].find, arr);
break;
}
}
console.log(findNode(json));
output for first iteration but not work for every iteration:
Object {id: 1, find: "orange", gotopage: "orange_store"}
Object {id: 2, find: "orange_store", gotopage: "yellow_store"}
1 Answer 1
Another example using recursion. I do a simple forEach() to find what you're looking for and store it in variables, log it, and re-call the function with our newly created values. If it doesn't find anything, it returns null and ends.
const data = [
{
"id": 1,
"find": "orange",
"gotopage": "orange_store"
},
{
"id": 2,
"find": "orange_store",
"gotopage": "yellow_store"
},
{
"id": 3,
"find": "black_store",
"gotopage": "black_store"
},
{
"id": 4,
"find": "yellow_store",
"gotopage": "white_store"
},
{
"id": 5,
"find": "black_store",
"gotopage": "red_store"
}
];
function recursiveStore(search, myArray) {
let obj = {}
let newSearch;
data.forEach(store => {
if (search === store.find) {
obj = store
newSearch = store.gotopage
}
})
if (Object.keys(obj).length === 0) {
return null
}
console.log(obj)
recursiveStore(newSearch, myArray)
}
recursiveStore("orange", data)
4 Comments
return instead - it would end there and not re-run itself. A function can only return one thing. You could do a couple of different things, like create an array outside of the object called stores and do something like stores.push(obj) instead of console.log(obj) and then still return recursiveStore(newSearch, myArray) and by the end, you'll have all the stores you need in one array of objects.Explore related questions
See similar questions with these tags.
searchRecbut never returning null. In javascript, indexing a missing element in an array will yieldundefinednotnull.