JavaScript - How to create nested unordered list based on nesting of array?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a nested array of arrays like this −

const arr = [
   'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'], 'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6' ];

We are required to write a JavaScript program that should map any such nested array of arrays of literals to nested unordered lists of HTML.

The only thing to take care of here is that the nesting of the ul has to be just identical to the nesting of the array.

Example

The code for this will be −

JavaScript Code 

const arr = [
   'Value 1', ['Inner value 1', 'Inner value 2', 'Inner value 3', 'Inner value 4'],
   'Value 2', 'Value 3', 'Value 4', 'Value 5', 'Value 6'
];
const prepareUL = (root, arr) => {
   let ul = document.createElement('ul');
   let li;
   root.appendChild(ul);
   arr.forEach(function(item) {
      if (Array.isArray(item)) {
         prepareUL(li, item);
         return;
      };
      li = document.createElement('li');
      li.appendChild(document.createTextNode(item));
      ul.appendChild(li);
   });
}
const div = document.getElementById('myList');
prepareUL(div, arr);

HTML Code 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="myList"></div>
</body>
</html>

Output

And the output will be −

raja
Published on 25-Nov-2020 06:55:34
Advertisements