Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript map function creates extra comma

This is my html file :

  function showMovies(){
    const movies = [
    {title: 'a nice movie', year: 2020, rating: 4.5},
    {title: 'another nice movie', year: 2021, rating: 4.8},
    {title: 'just another movie', year: 2022, rating: 4.2}
  ];
  
  let html ="";
  html = movies.map(function(m) {
    return "<li>" + m.title + '-' + m.year + "-"  + m.rating + "</li>";
  });

  html = "<ul>" + html + "</ul>";
  
  document.getElementById('list').innerHTML = html;
  
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>  
  </head>
  <body onload="showMovies()">
    <h2>List of movies</h2>
    <div id="list"></div>
    <script src="movies.js"></script>
  </body>
</html>

When I preview the page, I have extra commas like in the image below :
enter image description here

Is this an expected outcome with map function? Should I chain some joining/splitting fucntions to get rid of the extra commas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you do this:

html = "<ul>" + html + "</ul>";

html was an array, but you’re treating it as a string. In doing so, JavaScript is representing it as a set of comma-separated values.

Instead of implicitly converting the array to a string, you can explicitly join it to a string:

html = "<ul>" + html.join("") + "</ul>";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading