[javascript] Create a <ul> and fill it based on a passed array

I've managed to generate a series of list-items based on one specified array within a matrix (i.e. an array within an array).

I would like to be able to pass a variable (representing an array) to a function so that it can spit out an unordered list filled with list-items based on the array passed into it.

Problems:

  • The function only works with one array at a time
  • It also produces commas in the markup (presumably, because it's converting the array to a string)

The solution needs to:

  • assume that the unordered list does not exist in the DOM
  • be able to accept different arrays passed into it (options[0], options[1], etc.)
  • generate the list-items without commas

JavaScript:

var options = [
        set0 = ['Option 1','Option 2'],
        set1 = ['First Option','Second Option','Third Option']
    ]

function makeUL(){
    var a = '<ul>',
        b = '</ul>',
        m = [];

    // Right now, this loop only works with one
    // explicitly specified array (options[0] aka 'set0')
    for (i = 0; i < options[0].length; i += 1){
        m[i] = '<li>' + options[0][i] + '</li>';
    }

    document.getElementById('foo').innerHTML = a + m + b;
}

// My goal is to be able to pass a variable
// here to utilize this function with different arrays
makeUL();

jsFiddle

This question is related to javascript arrays

The answer is


What are disadvantages of the following solution? Seems to be faster and shorter.

var options = {
    set0: ['Option 1','Option 2'],
    set1: ['First Option','Second Option','Third Option']
};

var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;