Skip to content

Instantly share code, notes, and snippets.

@frumbert
Last active January 15, 2016 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frumbert/394ac0f6f7d1be1a64d1 to your computer and use it in GitHub Desktop.
Save frumbert/394ac0f6f7d1be1a64d1 to your computer and use it in GitHub Desktop.
Nested list from a flat array
var pages = [{
title: "alice",
depth: 0
},{
title: "bob",
depth: 1
},{
title: "charles",
depth: 1
},{
title: "delilah",
depth: 1
},{
title: "everett",
depth: 0
},{
title: "francais",
depth: 1
},{
title: "gloria",
depth: 1
},{
title: "harold",
depth: 1
},{
title: "ingrid",
depth: 2
},{
title: "jake",
depth: 0
}];
var html = [];
for (var i=0;i<pages.length;i++) {
var p = pages[i],
q = pages[i+1],
r = true;
if (q) {
if (q.depth > p.depth) {
html.push("<li>" + p.title + "<ol>");
r = false;
} else if (q.depth < p.depth) {
html.push("<li>" + p.title + "</li>");
for (j=0;j<p.depth;j++) html.push("</li></ol>");
r = false;
}
}
if (r) {
html.push("<li>" + p.title + "</li>");
}
}
var ol = document.createElement("ol");
ol.innerHTML = html.join("");
document.body.appendChild(ol);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment