I have the following array and I want to create an unordered list from it, but I am having trouble generating the unordered list in the proper format. I have searched similar questions but none of the existing solutions work for my problem.
JavaScript
x
2
1
var myArray = ['Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'], 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'];
2
Here is my JavaScript code:
JavaScript
1
19
19
1
function arrToUl(arr) {
2
var div = document.getElementById('myList');
3
var ul = document.createElement('ul');
4
5
for (var i = 0; i < arr.length; i++) {
6
7
if (arr[i] instanceof Array) {
8
var list = arrToUl(arr[i]);
9
} else {
10
var li = document.createElement('li');
11
li.appendChild(document.createTextNode(arr[i]));
12
console.log(ul.appendChild(li));
13
}
14
div.appendChild(ul);
15
}
16
}
17
18
arrToUl(myArray);
19
The above code is producing the following result:
JavaScript
1
12
12
1
<ul>
2
<li>Value 1</li>
3
<li>Inner Value 1</li>
4
<li>Inner Value 2</li>
5
<li>Inner Value 3</li>
6
<li>Inner Value 4</li>
7
<li>Value 2</li>
8
<li>Value 3</li>
9
<li>Value 4</li >
10
<li>Value 5</li >
11
<li>Value 6</li>
12
But the result should look like below:
JavaScript
1
15
15
1
<ul>
2
<li>Value 1
3
<ul>
4
<li>Inner Value 1</li>
5
<li>Inner Value 2</li>
6
<li>Inner Value 3</li>
7
<li>Inner Value 4</li>
8
</ul>
9
</li>
10
<li>Value 2</li>
11
<li>Value 3</li>
12
<li>Value 4</li>
13
<li>Value 5</li>
14
<li>Value 6</li>
15
Thank you for your help.
Advertisement
Answer
You’ve appended all the <ul>
elements to the myList <div>
. To change that, I’ve added a new parameter to the arrToUl(root, arr)
function.
The new parameter, root
, determines who the created <ul>
should be appended to, so if the function encounters a sub-array, it uses the previous list item as the root for the creation of the sub-list.
JavaScript
1
23
23
1
var myArray = ['Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'], 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'];
2
3
function arrToUl(root, arr) {
4
var ul = document.createElement('ul');
5
var li;
6
7
root.appendChild(ul); // append the created ul to the root
8
9
arr.forEach(function(item) {
10
if (Array.isArray(item)) { // if it's an array
11
arrToUl(li, item); // call arrToUl with the li as the root
12
return;
13
}
14
15
li = document.createElement('li'); // create a new list item
16
li.appendChild(document.createTextNode(item)); // append the text to the li
17
ul.appendChild(li); // append the list item to the ul
18
});
19
}
20
21
var div = document.getElementById('myList');
22
23
arrToUl(div, myArray);
JavaScript
1
1
1
<div id="myList"></div>