Reputation: 620
I am trying to recursively turn a nested array into an ordered HTML list.
My test array looks like: [['A','B','C'],['D',['E','F','G']]]
And the result should look like:
But it is currently returning:
When I print it out, the recursion is successful, but gets overwritten by the previous step. I feel like it has to do with declaring the string at the top of the function, but I am not sure how else to approach it.
JSFIDDLE: https://jsfiddle.net/nzyjoawc/2/
Upvotes: 3
Views: 114
Reputation: 115222
Do it with recursion and use Array#forEach
method for iterating over array.
var a = [
['A', 'B', 'C'],
['D', ['E', 'F', 'G']]
];
function gen(arr) {
// create `ol` eleemnt
var ol = document.createElement('ol');
// iterate over the array eleemnt
arr.forEach(function(v) {
// create list item `li`
var li = document.createElement('li');
// if array element is an array then do recursion
// and append the returnd value
if (Array.isArray(v))
li.appendChild(gen(v));
// else set the content as array value
else
li.innerHTML = v;
// append the list item to the list
ol.appendChild(li);
});
// resturn the genarated list
return ol;
}
document.body.appendChild(gen(a))
Upvotes: 3