What I want is something like Array.join(separator)
, but which takes a second argument Array.join(separator, beforeLastElement)
, so when I say [f
Building off of @dystroy's answer:
function formatArray(arr){
var outStr = "";
if (arr.length === 1) {
outStr = arr[0];
} else if (arr.length === 2) {
//joins all with "and" but no commas
//example: "bob and sam"
outStr = arr.join(' and ');
} else if (arr.length > 2) {
//joins all with commas, but last one gets ", and" (oxford comma!)
//example: "bob, joe, and sam"
outStr = arr.slice(0, -1).join(', ') + ', and ' + arr.slice(-1);
}
return outStr;
}
Example usages:
formatArray([]); //""
formatArray(["a"]); //"a"
formatArray(["a","b"]); //"a and b"
formatArray(["a","b","c"]); //"a, b, and c"
formatArray(["a","b","c","d"]); //"a, b, c, and d"