var arr = [h2, h3, h3, h2, h2, h2, h3, h4];
<ul>
<li>h2
<ul>
<li>h3</li>
<li>h3</li>
</ul>
</li>
<li>h2</li>
<li>h2</li>
<li>h2
<ul>
<li>h3
<ul>
<li>h4</li>
</ul>
</li>
</ul>
</li>
</ul>
var arr2 = ['h2', 'h3', 'h3', 'h2', 'h2', 'h2', 'h3', 'h4'];
function setList(arr) {
if (arr.length === 0) return '<ul>\n</ul>';
let fullList = '<ul>\n';
let ends = [];
arr.forEach((w,e) => {
if((arr[e+1]) && (parseInt(w[1]) < parseInt(arr[e+1][1]))){
fullList += `<li>${w}\n<ul>\n`;
ends.push('</ul>\n</li>');
} else if ((arr[e+1]) && (parseInt(w[1]) === parseInt(arr[e+1][1]))) {
fullList += `<li>${w}</li>\n`;
} else {
fullList +=`<li>${w}</li>\n` + ends.join('\n') + '\n';
ends = [];
}
})
fullList = fullList + '</ul>';
return fullList;
}
function createList(data) {
const list = document.createElement('ul');
const stack = [];
let level = +data[0].match(/\d+/);
let ul = list;
for (const n of data) {
const currLevel = +n.match(/\d+/);
if (currLevel > level) {
stack.push([ ul, level ]);
[ ul, level ] = [ document.createElement('ul'), currLevel ];
stack[stack.length - 1][0].lastElementChild.append(ul);
} else {
for (; currLevel !== level; [ ul, level ] = stack.pop()) ;
}
ul.insertAdjacentHTML('beforeend', `<li>${n}</li>`);
}
return list;
}