Last active
June 1, 2017 22:54
-
-
Save ScreamingHawk/201dfd4a6020c90cc74eff6e2430646a to your computer and use it in GitHub Desktop.
Convert Javascript array into human readable list
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
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