Join in array creating elements?

Asked

Viewed 91 times

2

We can imagine the following array:

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

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

Note: I know that I can also loop and do this using other methods, I would just like to reduce code even.

2 answers

3


Just combine the join with the 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 the reduce:

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

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

console.log(result)

  • Really needs the map?

  • @Wallacemaxters is not really a matter of necessity - in this example, but it’s simpler for you to work with the separate element. What do you do on map will be reflected in all. Think that now you need to put a <a> within the <li>.

  • You’re right. And depending on the situation, I would even appeal to a document.createElement to look more elegant :p

3

Thus?

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

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

console.log(html)

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

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

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

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

Besides the example above, you could do something more elaborate, with document.createElement, to create the li already within 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.