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


In this problem statement, our task is to to create a nested unordered list based on nesting of arrays with the help of Javascript. So for doing this task we will use a function to call recursively for each nested array and create a new unordered list..

Understanding the problem statement

In the above problem statement we have to create a function for a nested list in HTML using Javascript. The input for the code will be an array that can have any number of items and can also include other arrays that represent nested lists.

The code will be using a recursive function to traverse the given input array and develop new HTML elements like ui, li and text nodes as needed to generate the desired list structure. The resultant list is concatenated to a specific element in the HTML document identified by ID.

For example −

  • Tea

  • Cold drink

  • Coffee

  • Milk Shake

The above list is an unordered list showing with the help of dotted points.

Algorithm

Step 1 − First create a HTML file and inside this file we have to include our Javascript code for creating an unordered list. And create a div and give id as jsList, where we need to show the list on the front end

Step 2 − Define an nested array having list items.

Step 3 − Define a function called createNestedList and pass a parameter of a nested array.

Step 4 − Declare a variable to store the unordered list items with the help or createElement.

Step 5 − Start a for loop to loop through the array elements and to add the nested list in list tag.

Step 6 −Check whether the condition that the array has elements in it or not. If the condition is true then append it otherwise go to the else part.

Step 7 − Check if the item has a nested element so append as child to the node we have created.

Step 8 − At the last return the unordered list created using a nested array.

Code for the algorithm

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

      <script>
         //create a nested list
         const arr = [
            'Coffee', ['Cappuccino', 'Americano', 'Espresso', 'Mocha'],
            'Tea', ['Milk Tea', 'Black Tea'], 'Milk'
         ];
         //function to show the nested list on page
         function createNestedList(arr) {
            const ul = document.createElement('ul');
            for (let i = 0; i < arr.length; i++) {
               const li = document.createElement('li');
               if (Array.isArray(arr[i])) {
                  li.appendChild(createNestedList(arr[i]));
               } else {
                  li.appendChild(document.createTextNode(arr[i]));
               }
               ul.appendChild(li);
            }
            return ul;
         }
         const div = document.getElementById('jsList');
         div.appendChild(createNestedList(arr));
      </script>
   </body>
</html>

Complexity

The time complexity for the code is O(n) in which n is the total number of elements in the given input array because every element is traversed and processed one time. But the space complexity can be higher because of the recursive function which can create a large number of new HTML elements and store it on the calling stack.

Conclusion

The above code is the example of creating a nested unordered list with the help of a nested array in Javascript. The code gives a flexible and efficient way to produce nested lists in HTML with the help of Javascript. But this code should be used carefully when we are dealing with large nested arrays to avoid any issues with memory usage and stack overflow.

Updated on: 18-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements