Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ReactJS Intersperse with Typescript
/*
* intersperse: Return an array with the separator interspersed between
* each element of the input array.
*
* https://stackoverflow.com/questions/23618744/rendering-comma-separated-list-of-links
*
* > _([1,2,3]).intersperse(0)
* [1,0,2,0,3]
*
* This version is done in Typescript and supports React Elements.
*/
export default function Intersperse({
arr,
sep,
}: {
arr: Array<JSX.Element | string>;
sep: string | JSX.Element;
}): JSX.Element {
if (arr.length <= 1) return <></>;
const merged: JSX.Element | string = arr.reduce((prev: JSX.Element | string, curr: JSX.Element | string) => (
<>{[prev, sep, curr]}</>
));
return <>{merged}</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment