Recursive function returns undefined
In this arm of your function:
if (taxWage > minWage) {
// calculates tax recursively calling two other functions difference() and taxStep()
tax = tax + difference(taxWage) * taxStep(taxWage);
var newSalary = taxWage - difference(taxWage);
taxes(tax, newSalary);
}
you are not returning a value from the function or setting returnTax
. When you don't return anything, the return value is undefined
.
Perhaps, you want this:
if (taxWage > minWage) {
// calculates tax recursively calling two other functions difference() and taxStep()
tax = tax + difference(taxWage) * taxStep(taxWage);
var newSalary = taxWage - difference(taxWage);
return taxes(tax, newSalary);
}
Javascript recursive function returns undefined
areas.forEach(a => {
return fron the lambda function
. it is not returning from parent function. Use basic for loop to break loop.
For more info, you can read my blog: how-to-break-the-loop-in-javascript
class AreaManager {
constructor() {
this.areas = [];
this.areas.push(new Area("Area1", this));
this.areas[0].areas.push(new Area("AreaABC", this.areas[0]));
this.areas[0].areas[0].areas.push(
new Area("AreaABC123", this.areas[0].areas[0])
);
this.areas[0].areas.push(new Area("AreaDEF", this.areas[0]));
}
findAreaById(id, areas = this.areas) {
let merged = [];
for (let i = 0; i < areas.length; i++) {
if (areas[i].id == id) return areas[i];
merged = merged.concat(areas[i].areas);
}
return this.findAreaById(id, merged);
}
}
class Area {
constructor(id, parent) {
this.id = id;
this.areas = [];
}
}
var _Manager;
function InitManager() {
_Manager = new AreaManager();
}
function GetSomeArea() {
var searchID = "AreaDEF";
var areaObject = _Manager.findAreaById(searchID);
console.log(areaObject); //this is always undefined
}
InitManager();
GetSomeArea();
Recursive function on sorted array returns undefined
You're not calling the recursive
function from outside of the function.
const sortArray = (mainArr) => {
let acc = [];
console.log(acc, "acc");
const recursive = (arr) => {
if (arr.length > 1) {
console.log("inside func2 ", acc);
let likeArr = singArr(arr, arr[0]);
console.log(likeArr, "like");
arr = deleteVal(arr, arr[0]);
acc.push(likeArr);
return recursive(mainArr);
}
else {
return acc;
}
}
return recursive(mainArr)
};
Also, I believe the code posted doesn't return the desired output. You can probably do the following:
const array1 = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];
array1.sort((a,b) => a-b);
const map = new Map();
array1.forEach((item) => {
if(map.has(item)) {
const storedItem = map.get(item);
map.set(item, Array.isArray(storedItem) ? [...storedItem, item] : [storedItem, item])
} else {
map.set(item, item);
}
});
console.log(Array.from(map.values()))
JavaScript + recursive function returning undefined
You are simply the call to return
on the recursive call. Also, you should test whether its result is defined. If yes, you can return it, or continue looping if not.
var h = hasId(container, 'head');
var l = hasId(container, 'left');
var r = hasId(container, 'right');
console.log(h + " : " + r + " : " + l);
//[object HTMLDivElement] : undefined : undefined
function hasId(ele, id) {
for (var i = 0; i < ele.childNodes.length; i++) {
var child = ele.childNodes[i];
if(child.id == id) return child;
else {
var next = hasId(child, id);
if(next) return next;
};
}
}
Javascript recursion function returning undefined
Your recursive call have to return the value to the caller
function searchLeft(node, path) {
if (typeof node.left == 'undefined') {
console.log(path);
return path;
}
node = JSON.parse(JSON.stringify(node.left));
path.push(node.data);
return searchLeft(node, path); //here return
}
Why is my recursive function returning undefined?
forEach
does not return a value. If you want to sum all the results, you can use Array#reduce
. In addition, you can set the accumulator's initial value to 0
by passing in a second argument, so you can remove the check for the array's length being 0
.
function findNestedBags(key, color, data) {
if (data[key].includes(color)) {
return 1
} else {
return data[key].reduce((acc,item) => {
return acc + findNestedBags(item, color, data)
}, 0)
}
}
Recursive function returns undefined regardless of enough return statements
forEach
returns undefined
, so
return node.forEach(el => {
return recurseFind(el, id);
});
will always return undefined
, no matter what the recursive calls find.
I'd use a for
loop instead, and if a match is found, return it:
let animals = [
{
name: "dogs",
id: 1,
children: [
{
name: "lessie",
id: 2
},
{
name: "bark-a-lot",
id: 3
}
]
},
{
name: "cats",
id: 4,
children: [
{
name: "meows-a-lot",
id: 5,
children: [
{
name: "meows-a-lot-in-the-morning",
id: 6
}
]
},
{
name: "whisk-ass",
id: 7
}
]
}
];
function recurseFind(node, id) {
if (Array.isArray(node)) {
for (const el of node) {
const result = recurseFind(el, id);
if (result) return result;
}
} else {
if (node.id === id) {
return node;
} else if (node.children) {
for (const child of node.children) {
const result = recurseFind(child, id);
if (result) return result;
}
}
}
}
const found = recurseFind(animals, 6) || 'not found';
console.log("found", found);
Recursive async function returning undefined
Essentially the only problem with your code is that you don't await the results from you async function comp()
. map()
will return an array of Promises and you will need to await all those promises which you can do by using Promise.all()
. Promise.all()
returns a Promise which will resolve when all Promises in the array passed to Promise.all()
are settled. If you await that your children array will be propagated as you expect it to.
Here is your code with using Promise.all()
. Because I don't have a suitable database ready at the moment I replaced all your asynchronous calls to the database with an asynchronous call to a function which has an artificial delay built-in so you can see how to actually await those and that the result is actually awaited.
const data = [
{
id: 1,
task: "Clean apartment",
completed: 0,
parentid: null,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 2,
task: "Clean bathroom",
completed: 0,
parentid: 1,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 3,
task: "Clean kitchen",
completed: 0,
parentid: 1,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 4,
task: "Wash shower",
completed: 0,
parentid: 2,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 5,
task: "Wash toilet",
completed: 0,
parentid: 2,
createdby: 1,
createDate: "2022-03-24 00:47:33",
},
{
id: 6,
task: "Clean glass panes",
completed: 1,
parentid: 4,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 7,
task: "Clean faucet",
completed: 0,
parentid: 4,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 8,
task: "Clean sink",
completed: 0,
parentid: 3,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
{
id: 9,
task: "Take out trash",
completed: 1,
parentid: 3,
createdby: 1,
createdat: "2022-03-24 00:47:33",
},
];
async function comp(tasks, taskId) {
// do your DB calls here (here just imitating the delay but the function are async to the result will remain the same)
var task = await queryFind(tasks, taskId);
var children = await queryFilter(tasks, taskId);
// map() returns an array of promises as comp() returns a promise
// Promise.all() returns a Promise that returns when all promises within the array are settled
task.children = await Promise.all(
children.map((child) => comp(tasks, child.id))
);
return task;
}
// this function immitates an async DB access.
async function queryFind(tasks, taskId) {
// wait for 100 milliseconds (imitate delay)
await sleep(100);
return tasks.find((task) => task.id === taskId);
}
// this function immitates an async DB access.
async function queryFilter(tasks, taskId) {
// wait for 100 milliseconds (imitate delay)
await sleep(100);
return tasks.filter((t) => t.parentid === taskId);
}
// delay execution. should imitage network delay here
async function sleep(ms) {
return new Promise((resolve) => setTimeout(() => resolve(), ms));
}
// Start at task with ID 1; need to wrap the function call in an async method to be able to use await
(async () => {
const test = await comp(data, 1);
console.log(JSON.stringify(test, null, 4));
})();
Related Topics
How to Sort an Array of Integers Correctly
How to Detect Safari, Chrome, Ie, Firefox and Opera Browsers
How to Execute a JavaScript Function When I Have Its Name as a String
Getting a Random Value from a JavaScript Array
Share Data Between Angularjs Controllers
Creating a Blob from a Base64 String in JavaScript
JavaScript Object: Access Variable Property by Name as String
When Is JavaScript'S Eval() Not Evil
How to Use Multiple Versions of Jquery on the Same Page
How to Access Object Properties Containing Special Characters
How to Disable Right Click on My Web Page
Use Async Await With Array.Map
How to Prevent a Parent'S Onclick Event from Firing When a Child Anchor Is Clicked
In JavaScript, Does It Make a Difference If I Call a Function With Parentheses