Array to comma separated string
15 December 2023 (Updated 15 December 2023)
export function arrayToCommaSeparatedString(
arr: Array<string | number>,
): string {
if (arr.length === 0) {
return ''
}
if (arr.length === 1) {
return arr[0].toString()
}
if (arr.length === 2) {
return `${arr[0]} and ${arr[1]}`
}
return (
arr.slice(0, arr.length - 1).join(', ') + ', and ' + arr[arr.length - 1]
)
}
console.log(arrayToCommaSeparatedString(['foo', 'bar']))
console.log(arrayToCommaSeparatedString(['foo', 'bar', 'baz']))
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment