Created
July 23, 2015 11:14
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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; | |
} |
… 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
You could completely omit the
outStr
variable, and just directly return the result.