Array.join
is useful because it glues together an array of strings by a delimiter taking into account empty arrays and not padding the delimiter at either end of the output string.
I am making a React application and I would like find a similar native function, however, my array of React.ReactNode
elements is going to be mapped and rendered, so instead of joining the array with a delimiter and outputting a string, I just want to join the array with a string delimiter, but maintain the Array structure. Is there something already native to javascript/typescript/react that I can use to achieve the below psuedo-code?
let parts: React.ReactNode[] = [];
if (conditionA) {
parts.push(<div>Component One</div>);
}
if (conditionB) {
parts.push(<div>Component Two</div>);
}
parts = joinByDelimiterButKeepAsArray(parts, '|');
// I wants parts to now equal
// [<div>Component One</div>, '|', <div>Component Two</div>]
// if conditionA and conditionB are both true
return (
<>
{parts.map((part, i) => return (
<React.ReactFragment key={i}>{part}</React.ReactFragment>
))}
</>
)
Welp, kind of answered my own question. Currently, I use the following function to achieve this:
function joinByDelimiterButKeepAsArray<T>(a: T[], delimiter: T): T[] {
return a.flatMap((n, i) => (i + 1 < a.length ? [n, delimiter] : [n]));
}
Example:
const parts: React.ReactNode[] = [];
parts.push(<div>Component One</div>);
console.log(joinByDelimiterButKeepAsArray(parts, '|'));
/// [{...}]
parts.push(<div>Component Two</div>);
console.log(joinByDelimiterButKeepAsArray(parts, '|'));
/// [{...}, '|', {...}]
parts.push(<div>Component Three</div>);
console.log(joinByDelimiterButKeepAsArray(parts, '|'));
/// [{...}, '|', {...}, '|', {...}]