0

I need to represent Given array :

    ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"]

as single string separated by commas:

    'Alabama, Alaska, Arizona, Arkansas, California, Colorado'
n3018
  • 121
  • 2
  • 10

3 Answers3

2

Use the join function:

var myArray = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"];
var myString = myArray.join(', ');
console.log(myString);
Matthew Cawley
  • 2,688
  • 1
  • 8
  • 19
1

I'm nowhere near being really good at Angular, but couldn't you just write a js function to do it for you?

And I'm assuming you switched your 2 sentences? Since you want to go from array to string but your first line of code is a string and your second one is an array?

Anyway, this is how I would do it:

var string = "";

myStates.forEach(function (state, index, array) {
    if (index === array.length - 1) {
        string += state;
    } else {
        string += state + ", ";
    }
});
Dax
  • 203
  • 2
  • 7
0

Use this,

var a = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"];
var string = a.join(",");
console.log(string);
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32