Join in array creating elements?

1

We can imagine the following array :

var arr = ["a", "b", "c", "d"];

I know I can use join(", ") to make it into a string type: "a, b, c, d" , but I would like to create an element for each array item, which would be type: "<li>a</li> <li>b</li> <li>c</li> <li>d</li>" , you can do this using the join() ?

Note: I know I can also loop and do this using other methods, I'd just like to reduce code myself.

    
asked by anonymous 26.07.2018 / 18:06

2 answers

2

Just combine join with map :

const result = arr.map(it => '<li>${it}</li>').join(' ')

See working:

const arr = ["a", "b", "c", "d"]

const result = arr.map(it => '<li>${it}</li>').join(' ')

console.log(result)

Or with reduce :

const arr = ["a", "b", "c", "d"]

const result = arr.reduce((res, it) => res + '<li>${it}</li>', '')

console.log(result)
    
26.07.2018 / 18:10
2

So?

var arr = [1, 2, 3, 4, 5];

var html = "<li>" + arr.join("</li><li>") + "</li>";

console.log(html)

The idea is that you use </li><li> as the concatenation object.

arr.join('</li><li>') will generate this:

 "1</li><li>2</li><li>3"

So, just add <li> at start and </li> at the end of this string generated by join .

In addition to the above example, you could do something more elaborate, with document.createElement , to create li already inside a ul , for example:

var arr = [1, 2, 3, 4, 5];


var ul = document.createElement('ul');

arr.forEach(function (value) {

     var li = document.createElement('li');
     
     li.innerText = value;
     
     ul.append(li);
})



console.log(ul.outerHTML);
    
26.07.2018 / 18:10