Convert array to comma delimited text

Sorry for this inconveniently simple question, but I'm still relatively new to javascript.

I have an array of names, something like

var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];

I would like to return a string with names separated by commas, but with a "and" between the last two names, i.e.

'Hill M, Zhang F, Dong L, Wilkinson JS and Harris N'

What is the most efficient way to do this in javascript?

How about if I need to rearrange the names and initials, i.e. to return

'M Hill, F Zhang, L Dong, JS Wilkinson and N Harris'
+5
source share
4 answers

Array:: slice() .
Array:: join()
String:: concat() .

var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];

console.log(myArray.slice(0, myArray.length - 1).join(', ').concat(
            ' and ' + myArray[myArray.length - 1]));

//Hill M, Zhang F, Dong L, Wilkinson JS and Harris N

:

var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];

for(var i = 0; i < myArray.length; i++)
  myArray[i] = myArray[i].replace(/^(\S+)\s+(.+)$/, '$2 $1');

console.log(myArray.slice(0, myArray.length - 1).join(', ').concat(
            ' and ' + myArray[myArray.length - 1]));

//M Hill, F Zhang, L Dong, JS Wilkinson and N Harris

str.replace(/^(\S+)\s+(.+)$/, '$2 $1');

/^(\S+)\s+(.+)$/ - , , :

^    #starts with  
\S+  #one or more non whitespace characters, followed by  
\s+  #one or more whitespace characters, followed by  
.+   #one or more characters  

$1 $2 1- 2- (, ) .

+19

join .

var myJoinedString = myArray.join(',');
+8
var myArray = ['Hill M','Zhang F','Dong L', 'Wilkinson JS', 'Harris N'];
var replaced = myArray.map(function(elem) {
  return elem.replace(/(\S+)\s+(\S+)/, "$2 $1");
});
var last = replaced.pop()
var result = replaced.join(", ") + " and " + last;

alert(result)
+2
source

Try the following:

if (myArray.length <= 1) {
    str = myArray.join();
} else {
    str = myArray.slice(0, -1).join(", ") + " and " + myArray[myArray.length-1];
}

And for your swap part:

myArray.map(function(val) { return val.split(" ").reverse().join(" "); })
+2
source

All Articles