Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active December 18, 2023 12:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieMason/c1a089f6f1f147dbe9f82cb3e25cd12e to your computer and use it in GitHub Desktop.
Save JamieMason/c1a089f6f1f147dbe9f82cb3e25cd12e to your computer and use it in GitHub Desktop.
Format JavaScript Array of Strings to Oxford Comma.

Format JavaScript Array of Strings to Oxford Comma

const toOxfordComma = (array) =>
  array.length === 2
    ? array.join(' and ')
    : array.length > 2
    ? array
        .slice(0, array.length - 1)
        .concat(`and ${array.slice(-1)}`)
        .join(', ')
    : array.join(', ')

Usage

toOxfordComma(['Apples'])
// Apples
toOxfordComma(['Apples', 'Bananas'])
// Apples and Bananas
toOxfordComma(['Apples', 'Bananas', 'Pears'])
// Apples, Bananas, and Pears
toOxfordComma(['Apples', 'Bananas', 'Pears', 'Oranges'])
// Apples, Bananas, Pears, and Oranges
@calvin-cdev
Copy link

thanks for sharing this! thought i'd let you know it fails with a list of 2. ['apple', 'orange'] comes out as apple, orange but should be apple and orange.

@JamieMason
Copy link
Author

Thanks a lot @calvin-summer, good spot.

@JamieMason
Copy link
Author

Thanks @calvin-summer, fixed.

@maurer2
Copy link

maurer2 commented Aug 6, 2022

Hello, I believe you can just use:

const listFormatter = new Intl.ListFormat('en', { style: 'long' });
listFormatter.format(['Apples', 'Bananas', 'Pears', 'Oranges'])

Cheers

@JamieMason
Copy link
Author

Nice, Browser support looks pretty good now too vs 2019 when I wrote this – thanks for the tip.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment