Skip to content

Instantly share code, notes, and snippets.

@ScreamingHawk
Last active June 1, 2017 22:54
Show Gist options
  • Save ScreamingHawk/201dfd4a6020c90cc74eff6e2430646a to your computer and use it in GitHub Desktop.
Save ScreamingHawk/201dfd4a6020c90cc74eff6e2430646a to your computer and use it in GitHub Desktop.
Convert Javascript array into human readable list
function humanifyArray(arr, lastWord){
if (!arr || arr.length === 0){
// Return an empty string for blank arrays
return ''
} else if (arr.length == 1){
// Return the sole array item if only 1 item
return arr[0]
}
// Duplicate array to prevent modification issues
arr = arr.slice(0)
let last = arr.pop()
// Default lastWord to 'and' if none supplied
lastWord = lastWord || 'and'
// Combine and return
return arr.join(', ') + ' ' + lastWord + ' ' + last
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment