How can I turn an array, such as ["Susy", "John", "Mary"]
to "Susy, John, and Mary"
in Javascript? I can't get Ruby's to_sentence method out of my head.
12 Answers
Using newest JavaScript (Chrome 72+):
new Intl.ListFormat().format(["Susy", "John", "Mary"]);
which will result in:
"Susy, John, and Mary"
-
2Whoa, this is going to be great, when it's supported! developers.google.com/web/updates/2018/12/intl-listformat Jan 14, 2019 at 21:34
-
Awesome! But unfortunately still poorly supported by other browsers :( caniuse.com/#search=ListFormat– morglerApr 9, 2020 at 23:41
Join all items except the last one, and then add that:
var s = arr.slice(0, arr.length - 1).join(', ') + ", and " + arr.slice(-1);
-
1Just one note- Americans put a comma before the "and". OP has done this. Feb 8, 2013 at 1:01
-
-
9I can see a couple of problems with this method. If there's only 1 element in the array, it will return ", and Susy". For two elements, it returns "Susy, and John", which isn't grammatically correct.– AlexApr 12, 2014 at 5:27
-
@Alex: Yes, with less that three items you need additional code, but that's outside the scope of the question. There is no answer here that handles that case.– GuffaApr 12, 2014 at 10:31
-
Good point, but I think if you're only concerned with the specific use case presented, you could end up with something like jAndy's (joke) answer :-) I've posted an answer that covers the most obvious cases I could think of.– AlexApr 12, 2014 at 22:19
Another option, using Array.prototype.reduce
, would be:
var arr = [1,2,3];
arr.reduce(
function(prev, curr, i){
return prev + curr + ((i===arr.length-2) ? ' and ' : ', ')
}, '')
.slice(0, -2);
Produces "1, 2 and 3"
.
toSentence = function(arr){ return arr.join(", ").replace(/,\s([^,]+)$/, ' and $1');};
toSentence(['dogs', 'cats']); // => dogs and cats
toSentence(['dogs', 'cats', 'snakes']); // => dogs, cats and snakes
There are a few extra cases in this one:
- Do we want to have a comma before the "and" (Oxford Comma)
- Either way, we don't want a comma if there are only 2 elements
- If there is only 1 element, we just want that word returned
I think this fits all of those use cases:
function joinSentence( array, oxford_comma ){
if( array.length > 1 ){
var lastWord = " and " + array.pop();
if( oxford_comma && array.length > 1 ){
lastWord = "," + lastWord;
}
}else{
var lastWord = "";
}
return array.join(", ") + lastWord;
}
And another solution:
(function(a) {
var b = (a||(a=[])).pop();
return (b ? a.length ? [a.join(", "),b] : [b] : a).join(" and ");
})(["Susy", "John", "Mary"]);
or just defining your ruby-like sentence method in array's prototype:
Array.prototype.sentence = function(comma,and) {
var b = this.pop();
return (b ? this.length ? [this.join(comma||", "),b] : [b] : this).join(and||" and ");
};
["Susy", "John", "Mary"].sentence();
//"Susy, John and Mary"
["Susy", "John", "Mary"].sentence(" and ", " as well as ");
//"Susy and John as well as Mary"
["Susy", "John", "Mary", "Helmut"].sentence();
//"Susy, John, Mary and Helmut"
modify the last then join
var source = ["Susy", "John", "Mary"];
source.push( 'and ' +source.pop());
console.log(source.join(', '))// Susy, John, and Mary
-
ok this is sexier :) But is it grammatically correct to add a comma before and?– mikaFeb 8, 2013 at 1:02
-
Doesn't work for 1 and 2 elements: ["Susy"] => "and Susy". ["Susy", "John"] => "Susy, and John" May 9, 2017 at 19:59
Try that:
var array = ['susy', 'john', 'mary'];
var last = array.pop();
var string = array.join(', ') + " and " + last;
i didn t try but you should get the idea
You can use .join() and prepend the last value with an "and"
var array = ['susy', 'john', 'mary'];
array[array.length-1] = 'and '+array[array.length-1];
//string is "susy, john, and mary"
var string = array.join(', ');
A very simple way to do it:
function toSentence(array) {
const lastWord = (array.length > 1) ? ` and ${array.pop()}` : ''
return array.join(', ') + lastWord
}
There is actually an easier way these days, just use method join();
For example, let array = ["Susy", "John", "Mary"];
array.join();
This will return Susy,John,Mary
var arr = ["Susy", "John", "Mary"];
var str = arr.join(", ");
-
3
["Susy", "John", "Mary"].join(',').split(/,M/).join(' and M');