Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a nested ordered list from array data

I have data like this:

var array = ["a", "b", "c", "d", "e"];

I want this data converted like this:

<ol>
 <li>a</li>
   <ol>
    <li>b</li>
     <ol>
      <li>c</li>
       <ol>
        <li>d</li>
       </ol>
     </ol>
  </ol>

I will try this:

var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '<ol>';
    nested += '<li>' + el + '</li>';
    makeNestedList();
    nested += '</ol>';
  });
};

But why is the result empty?

like image 745
adibfirman Avatar asked Nov 15 '17 14:11

adibfirman


2 Answers

You could use Array#reduceRight and create the most nested node first and then the outer ones.

var array = ["a", "b", "c", "d", "e"],
    result = array.reduceRight(function (r, a) {
        return '<ol><li>' + a + r + '</li></ol>';
    }, '');
    
document.body.innerHTML += result;
console.log(result);

From the outside to inside with nodes.

var array = ["a", "b", "c", "d", "e"];

array.reduce(function (node, item) {
    var ol = document.createElement('ol'),
        li = document.createElement('li');

    li.appendChild(document.createTextNode(item));
    ol.appendChild(li);
    node.appendChild(ol);
    return li;
}, document.body);
like image 162
Nina Scholz Avatar answered Oct 19 '22 23:10

Nina Scholz


You have number of problems in your code. You need to pass input array into function and return something from it. Then you don't need loop inside, since you are using recursion anyway.

Something like this I think will fix it:

var array = ["a", "b", "c", "d", "e"];

var makeNestedList = (arr) => {
  let nested = '<ol>'
  nested += '<li>' + arr[0];
  if (arr.length > 1) {
    nested += makeNestedList(arr.slice(1));
  }
  nested += '</li></ol>';
  return nested
};

document.body.innerHTML = makeNestedList(array)
like image 21
dfsq Avatar answered Oct 20 '22 00:10

dfsq