Is it possible to render array items into separate divs using the .map() method without displaying commas?

After extensive searching, I have only come across solutions that involve using .join() to combine the items into a single string.

const createCard = () => {
    const pokemonTypes = ['grass', 'fire', 'water'];
      return (
        `<div>
          ${pokemonTypes.map(type => `<div>${type}</div>`)}
        </div>`
      )
}

document.body.insertAdjacentHTML("beforeend", createCard());

To provide some background, I am working with an API, but I have simplified the code for readability and convenience.

My goal is to display each string in its own div, allowing me to style each div differently - for example, using green for grass, blue for water, and red for fire, creating color-coded buttons.

Upon running the code, the strings successfully display in their own divs, but the comma between them persists. I would prefer for them to be displayed side by side without any separation.

Answer №1

Array.map transforms an array into another array as the result. When you set this array as the html content, it is like converting the array into a string.

For instance

const numArray = [1, 2, 3];
console.log(numArray.toString());

Converting an array into a string will always result in commas between the elements.

Your code is equivalent to the following

document.body.insertAdjacentHTML("beforeend", [1, 2, 3]);

What you need to do is join this array with an empty string and set this single string as the html content as shown below.

Use .join('') to concatenate an array without commas

const createCard = () => {
  const pokemonTypes = ['grass', 'fire', 'water'];
  return (
    `<div>
      ${pokemonTypes.map(type => `<div>${type}</div>`).join('')}
    </div>`
  );
}

document.body.insertAdjacentHTML("beforeend", createCard());

Answer №2

When using the .map() method, an array is returned. Within the template literal `${}`, JavaScript will automatically convert this array into a string by default, separating elements with commas. If you want to join the array elements into a string without using a comma, you can do so manually:

${pokemonTypes.map(type => `<div>${type}</div>`).join('')}

Answer №3

You can utilize the .join('') method to concatenate strings and apply the same styling.

const createCard = () => {
  const pokemonTypes = ['grass', 'fire', 'water'];
  return (
    `<div>
      ${pokemonTypes.map(type => `<div class="${type}">${type}</div>`).join('')}
    </div>`
  );
}

document.body.insertAdjacentHTML("beforeend", createCard());
.grass {
  color: green
}

.fire {
  color: red
}

.water {
  color: blue
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we prevent the continual overwriting of Object values?

I'm currently working on extracting data from the USDA Food Data Central API. Specifically, I'm interested in retrieving the "name" and "amount" values under the "nutrient" section. The excerpt below shows the information retrieved: Input- repor ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Issue encountered while attempting to pass a function within the data in React

I've encountered an issue while trying to pass a function called sectionOne and then calling it from another component. The error message I received is quite confusing. Error: Warning: Functions are not valid as a React child. This may happen if you r ...

I developed a compact application utilizing Node.js in tandem with Express framework

There is an issue with the GPA calculator app built using Node.js and Express. It works fine for a single user, but when multiple users try to use it simultaneously, the scores are being combined, resulting in incorrect values. I need to create an app that ...

Display a compilation either in the backend or the frontend

I'm fairly new to NodeJS and I could really use some advice. I currently have a webpage that displays a list of users, which is retrieved from a collection using Mongoose. I am aware of two different ways to display this list: 1) One option is to que ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Is there a way to programmatically display an edit text field on an HTML page?

Currently, I have a straightforward task which involves pulling data from a MySQL database to display in an HTML table. Here is the current script: <html> <body> <table border='1'> <?php mysql_connect('url',&ap ...

What is the correct way to utilize JSON with AJAX?

I am looking to transfer data from a php backend to a browser using JSON. I have a basic understanding of the process and have included an example code snippet below. However, I have been advised that this may not be the most efficient approach. Due to my ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

Can a single value be stored in a table using a radio button?

I have created an HTML table that is dynamically generated from a database. I am using a for loop to populate the table. However, I am facing an issue where each radio button in the table holds only one value. What I actually want is for each row to have ...

Selection determines the value of two fields

This form has predefined values that are used to create a link, but the issue is that these values vary depending on the location. Can you assist me with this problem? <input type="radio" id="iconapp1" name="department" value="1250"/><label for ...

Surprising use of template string value

After following a tutorial, I decided to create ProductScreen.js and Product.js. However, when implementing my code, I encountered some warnings. Can anyone help me identify the issue? product.js import React from 'react' import Rating from &apo ...

Transient Flash of a jQuery Dropdown Menu

I'm currently developing a jQuery/CSS dropdown menu for a website, and everything is functioning well except for one issue. When navigating between sub-menu items, the text color of the selected main menu item briefly changes because of the CSS border ...

Bird's-eye view captured by a high-angle camera

As I rotate a sphere around the z-axis, I'm looking for a way to prevent the camera from causing motion sickness by creating a stable elevated view of the sphere. How can I achieve this without the camera's movements being so jarring? If you&apo ...

Eliminate an item from the output of an Active Record search

I'm currently navigating my way through the world of Rails and encountering a challenge with the output of an Active Record query. In my Class method (this_week), I retrieve 3 recipe records from the database. Now, I want to remove just one of these ...

Encountering issues with the display of JSON data in MVC

Question: How can I pass JSON data from my controller to the view and render it using JavaScript? [HttpGet] [AllowAnonymous] public ActionResult Index() { ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_C ...

Utilize a function from a separate JavaScript file by calling it within the $(document).ready(function()

Refer to this post for more information: Click here I attempted to access a function that was defined in another .js file based on the instructions from the post. However, I encountered an issue. Take a look at my code below: sildemenu.js $(document).re ...

A guide on seamlessly incorporating FlotJs functionalities into a ReactJs application

Having trouble integrating Flot charts into React due to a '$.plot' is not a function error. Here's the code I'm using: Script tags Index.html <script src="dist/libs/js/jquery.min.js"></script> <script src="dist/libs/js ...