Skip to content

Convert an array to a list using jQuery

Got a challenge to convert a two dimensional array to a html list. the array is like

var arr=[[1,"link1",3],[2,"link2",0],[3,"link3",2]]

The structure of the nested array item is id, textOfLink, parent. parent 0 means top level, parent 3 means the item is under another list item with id of 3. the target output will a list in html like


please note the array is not limited to 3 items, it is dynamic. any idea how to do it in jQuery?



Here’s my version:

var arr = [
    [1, 'link1', 3],
    [2, 'link2', 0],
    [3, 'link3', 2]

function processData(list) {
    var out = $('<ul>'), // or ol
        idMap = {};

    function get(id, text) {
        var $el = idMap[id] || (idMap[id] = $('<li><a></a></li>'));
        if (text) {
        return $el;

    function addChild($parent, $child) {
        var $list = $parent.children('ul');
        if (!$list.length) {
            $list = $('<ul>').appendTo($parent);

    var id,

    for (var i = 0, l = list.length, item; i < l; i++) {
        item = list[i];
        id = item[0];
        text = item[1];
        parentId = item[2];
        $el = get(id, text);

        if (parentId) {
            addChild(get(parentId), $el);
        } else {

    return out;


Why this is a good approach:

  • Everything is wrapped in a function -> reusable, clean, easy to maintain, no global variables are added exception functionName
  • You are getting what you want as an output (jQuery Element) for your input (data array)
  • If you look at my code, you can easily read and follow what I am each line.
  • Clean code