

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript - How to create nested unordered list based on nesting of array?
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 −
- Related Questions & Answers
- How to sort an array of objects based on the length of a nested array in JavaScript
- Un-nesting array of object in JavaScript?
- Manipulate Object to group based on Array Object List in JavaScript
- How to create an unordered list without bullets in HTML?
- How to create an unordered list without bullets using CSS?
- Sorting Array based on another array JavaScript
- Sort object array based on another array of keys - JavaScript
- How to create an unordered list with disc bullets in HTML?
- How to create an unordered list with circle bullets in HTML?
- How to create an unordered list with square bullets in HTML?
- How to create an unordered list with image bullets in HTML?
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Modify an array based on another array JavaScript
- Array Nesting in C++
Advertisements