Skip to content

Instantly share code, notes, and snippets.

@gayanvirajith
Created July 23, 2015 11:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gayanvirajith/6ed9f70b617122bcd2b6 to your computer and use it in GitHub Desktop.
Save gayanvirajith/6ed9f70b617122bcd2b6 to your computer and use it in GitHub Desktop.
Join the elements in an javascript array, but let the last separator be different eg: `and` / `or`
/*
* Join the elements in an javascript array,
* but let the last separator be different eg: `and` / `or`
* Stackoverflow link: http://stackoverflow.com/questions/15069587/is-there-a-way-to-join-the-elements-in-an-js-array-but-let-the-last-separator-b
* Credit: Chris Barr - http://stackoverflow.com/users/79677/chris-barr
*/
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;
}
@vlakoff
Copy link

vlakoff commented Jun 14, 2019

You could completely omit the outStr variable, and just directly return the result.

@vlakoff
Copy link

vlakoff commented Jun 14, 2019

… without forgetting to handle the arr.length === 0 case :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment