Below is an example on how countup is down using recursion
unction countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));
The above function is best explained here https://www.youtube.com/watch?v=p-cj4Vh8cMg
The important thing to note is , that the array elements start adding from 1 onwards , the countup(4) waits till countup(1) is done.
Use the above as an example and create a countdown function so it returns n to 1 numbers in an array when we pass n in countdown(n)
Things to consider, if you have no idea about unshift, you would try to add an element to an array by declaring a new array everytime the function is called , and it is not gonna work, but if you have an idea on how to use arguments you could solve this as follows
function countdown(n, newArr=[]) {
if (n <= 0) {
return newArr;
}
newArr.push(n);
return countdown(n - 1, newArr)
}
console.log(countdown(5));
So thats how you pass the argument array with its elements in the recursive function.
Now the shortest /imo best solution is using unshift in array methods as below , unshift does the same as push but in the opposite order , so it works out well.
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
Top comments (0)