I have data like this:
var array = ["a", "b", "c", "d", "e"];
I want this data converted like this:
<ol>
<li>a</li>
<ol>
<li>b</li>
<ol>
<li>c</li>
<ol>
<li>d</li>
</ol>
</ol>
</ol>
I will try this:
var makeNestedList = () => {
$.each(array, function(i, el) {
nested += '<ol>';
nested += '<li>' + el + '</li>';
makeNestedList();
nested += '</ol>';
});
};
But why is the result empty?
You could use Array#reduceRight
and create the most nested node first and then the outer ones.
var array = ["a", "b", "c", "d", "e"],
result = array.reduceRight(function (r, a) {
return '<ol><li>' + a + r + '</li></ol>';
}, '');
document.body.innerHTML += result;
console.log(result);
From the outside to inside with nodes.
var array = ["a", "b", "c", "d", "e"];
array.reduce(function (node, item) {
var ol = document.createElement('ol'),
li = document.createElement('li');
li.appendChild(document.createTextNode(item));
ol.appendChild(li);
node.appendChild(ol);
return li;
}, document.body);
You have number of problems in your code. You need to pass input array into function and return something from it. Then you don't need loop inside, since you are using recursion anyway.
Something like this I think will fix it:
var array = ["a", "b", "c", "d", "e"];
var makeNestedList = (arr) => {
let nested = '<ol>'
nested += '<li>' + arr[0];
if (arr.length > 1) {
nested += makeNestedList(arr.slice(1));
}
nested += '</li></ol>';
return nested
};
document.body.innerHTML = makeNestedList(array)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With