-
-
Save dark-reiser/eb63f9e9bb6c235685a99ab6eb986659 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 hidden or 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment