The problem is that your recursive call does not pass the second argument.
Without passing it, each recursive call will just populate its own, new array. It does return that array to the caller, but the caller (making the recursive call) ignores that returned value, so all the work of the recursive call is for nothing.
So the easy fix is to change this:
} else {
recursion(nE);
to this:
} else {
recursion(nE, resultAry);
Answer from trincot on Stack OverflowThe problem is that your recursive call does not pass the second argument.
Without passing it, each recursive call will just populate its own, new array. It does return that array to the caller, but the caller (making the recursive call) ignores that returned value, so all the work of the recursive call is for nothing.
So the easy fix is to change this:
} else {
recursion(nE);
to this:
} else {
recursion(nE, resultAry);
Try this:
function recursion(array, resultAry = []) {
array.forEach((element) => {
if (typeof element === "string") {
console.log(element);
resultAry.push(element);
} else {
nE = rndmElementSelection(element);
if (typeof nE === "string") {
console.log(nE);
resultAry.push(nE);
} else {
resultAry = [...resultAry, ...recursion(nE)];
}
}
});
return resultAry;
}
Referencing an Array inside a Recursive Function
Javascript recursion loop items to array - Stack Overflow
Help with Recursive Arrays
javascript - Looping through a recursive array - Stack Overflow
Videos
The problem is how you are passing the processing of array, if the value is an array then you are keep calling it causing an infinite loop
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
Demo: Fiddle
Here's a more modern version:
function flatten(items) {
const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});
return flat;
}
The clean way to flatten an Array in 2019 with ES6 is flat()
Short Answer:
array.flat(Infinity)
Detailed Answer:
const array = [1, 1, [2, 2], [[3, [4], 3], 2]]
// All layers
array.flat(Infinity) // [1, 1, 2, 2, 3, 4, 3, 2]
// Varying depths
array.flat() // [1, 1, 2, 2, Array(3), 2]
array.flat(2) // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat().flat() // [1, 1, 2, 2, 3, Array(1), 3, 2]
array.flat(3) // [1, 1, 2, 2, 3, 4, 3, 2]
array.flat().flat().flat() // [1, 1, 2, 2, 3, 4, 3, 2]
Mozilla Docs
Can I Use - 96% Oct '23
You're creating a new array instead of passing it to the recursive call.
Do this instead.
DEMO: http://jsfiddle.net/kDtZn/
function addToArray(array) {
array.push(prompt("Add items to array or 'q' to stop"));
if (array[array.length-1] == 'q') {
array.pop();
document.write(array)
}
else {
addToArray(array);
}
}
addToArray([]);
Now you start with an empty array, and for each recursive call, it passes the same array forward.
Also, I changed it so that it doesn't use .pop() in the if() condition, otherwise you'll always end up with an empty array when it comes time to write it. (The .pop() method actually removes the last item.)
Finally, make sure you're not using document.write after the DOM is loaded. If so, you need to change it to use DOM manipulation methods instead.
You could take a different approach so that you don't need .pop() at all.
DEMO: http://jsfiddle.net/kDtZn/1/
function addToArray(array) {
var item = prompt("Add items to array or 'q' to stop");
if (item == 'q') {
document.body.textContent = array;
} else {
array.push(item);
addToArray(array);
}
}
addToArray([]);
The reason your while loop didn't work is very likely because of the original .pop() issue.
Your function recreates var array = [] on every loop/recursion. I am not sure if recursion is the right tool for the job in your case - it does not seems like it - but if you're starting out with JavaScript/development and just trying it out then you're fine.
You need a recursive method to flatten a recursive array.
Here's a pretty basic one:
var data = ["1",
[
"2",
[
"3"
],
[
"4",
[
"5"
]
]
]];
var flattened = [];
function flatten(data, outputArray) {
data.forEach(function (element){
if(Array.isArray(element)) {
flatten(element, outputArray);
} else {
outputArray.push(element);
}
});
}
flatten(data, flattened);
This should get you moving in the right direction. Good luck!
I am not sure, but what you have presented looks more like an object. In such case it is quite easy to traverse through the nested object, eg.
var object = { 0: "1",
1: {
0: "2",
1: {
0: "3"
},
2: {
0: "4",
1: {
0: "5"
}
}
}};
console.info(object);
function traverse(obj) {
obj.keys.forEach(function(key) {
if (typeof(obj[key]) === 'object') {
traverse(obj[key])
}
else {
//do something with the actual value
console.log(obj[key])
}
})
};
traverse(object)
Can you specify what did you mean with I want the output to be the path of all the values?
If you don't need using recursion, this is an alternative where you can get rid of the second param of the function.
const stringToArray = (str) => {
const result = [];
let wordArray = str.split(' ');
while(wordArray.length > 0) {
result.push(wordArray.join(' '));
wordArray = wordArray.slice(1);
}
return result;
};
const partsArray = stringToArray('Chicago IL 12345 United States');
console.log(partsArray);
If you're targeting a recent javascript engine you can use default parameters which would save you line #2.
Additionally, to improve readability I'd recommend moving the string slicing to its own line, and I'd also use a name other than len to represent the number of words remaining. Clean Code by Robert Martin is a great resource for learning how to improve code readability.
const stringToArray = (str, result = []) => {
const wordArray = str.split(' ');
const numberOfRemainingWords = wordArray.length;
result.push(str);
if (numberOfRemainingWords === 1) {
return arr;
}
const remainingWords = wordArray.slice((-1 * numberOfRemainingWords) + 1).join(' ');
return stringToArray(remainingWords, result);
};
const partsArray = stringToArray('Chicago IL 12345 United States');
console.log(partsArray);
Hello there,
I am new to JS having a hard time figuring out how does recursion in this code works I know that push in Js almost works like append rather than just push
Code:
function countdown(n){
if(n<=0){
var arr=[];
return arr;}
if(n>0){
var arr=[n];
arr.push(countdown(n-1));
return arr;}}
console.log(countdown(5));
Output
[ 5, [ 4, [ 3, [Array] ] ] ]
Why does it print nested array
Thanks for help in advance;)