Home > Blockchain >  How to display all items from a javascript array in html with commas in between them except the last
How to display all items from a javascript array in html with commas in between them except the last

Time:04-13

I have to use a for loop or while loop. How do I include the last item from the array without including the comma afterward? Below I have the code that prints all items in the array except the last one.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="coffee.css" />
    <title>Coffee</title>
  </head>
  <body>
   
    <section >
      <h3>Drinks of the Month</h3>
      <p id="drinks"></p>
    </section>

    <script>
      var drinks = [
        "Chai Tea",
        "Sweet Cream Cold Brew",
        "Caramel Macchiato",
        "Vanilla Latte",
      ];

      var i = 0;
      var drinksOfMonth = "";
      while (i < drinks.length - 1) {
        drinksOfMonth  = drinks[i]   ", ";
        i  ;
      }


      document.getElementById("drinks").innerHTML = drinksOfMonth;
    </script>
  </body>
</html>

CodePudding user response:

Just use join() method of array.

Example

const foo = ['tea', 'coffee', 'soda'];

console.log(foo.join('-'));
console.log(foo.join(', ');

You can read more about Array.join() here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

CodePudding user response:

This will do it:

var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
]

drinks.join(', ')

Will output:

Chai Tea, Sweet Cream Cold Brew, Caramel Macchiato, Vanilla Latte

CodePudding user response:

You can also do it like this

while (i < drinks.length) { 
  if(i != drinks.length-1){
    drinksOfMonth  = drinks[i]   ", "}
  else{
    drinksOfMonth  = drinks[i]}
 i   
}

CodePudding user response:

I have to use a for loop or while loop. How do I include the last item from the array without including the comma afterward ?

Why you want to use for or while loop as you can easily achieve this requirement with Array.join() method with a single line of code.

Demo :

var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
];

console.log(drinks.join(', '));

CodePudding user response:

Just add the last item after the while loop:

drinksOfMonth  = drinks[drinks.length-1];
  • Related