How to process JavaScript nested array and display the order of numbers according to the level upto which they are nested?


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

const arr = [23, 6, [2,[6,2,1,2], 2], 5, 2];

We are required to write a program that should print the numbers (elements) of this array to the screen.

The printing order of the numbers should according to the level upto which they are nested.Therefore, the output for the above input should look like this −

23
6
   2
      6
      2
      1
      2
   2
5
2

Example

The code for this will be −

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf−8">
   <meta name="viewport" content="width=device−width">
   <title>PATTERN</title>
</head>
<body>
   <script>
      const arr = [23, 6, [2, [6, 2, 1, 2], 2], 5, 2];
      arr.reduce(function iter(level) {
         return function (node, item) {
            var pTag = document.createElement('p');
            pTag.style.marginLeft = level + 'px';
            node.appendChild(pTag);
            if (Array.isArray(item)) {
               item.reduce(iter(level || 50), pTag);
            } else {
               pTag.appendChild(document.createTextNode(item));
            }
            return node;
         };
      }(0), document.body);
   </script>
   <p></p>
</body>
</html>

And the output on the screen will be −

Updated on: 20-Nov-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements