Last active
January 15, 2016 02:21
-
-
Save frumbert/394ac0f6f7d1be1a64d1 to your computer and use it in GitHub Desktop.
Nested list from a flat array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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