This function intersperses a specific value between the elements of an array.
JavaScript:
let intersperse = (arr, sep) => arr.reduce((a, v, i) => [...a, v, ...(i === arr.length - 1 ? [] : [sep])], []);
// Example
console.log(intersperse([1, 2, 3], 'a')); // [1, 'a', 2, 'a', 3]
console.log(intersperse(['apple', 'banana', 'cherry'], ', ')); // ['apple', ', ', 'banana', ', ', 'cherry']
TypeScript:
let intersperse = (arr: T[], sep: T): T[] => arr.reduce((a, v, i) => [...a, v, ...(i === arr.length - 1 ? [] : [sep])], []);
// Example
console.log(intersperse([1, 2, 3], 'a')); // [1, 'a', 2, 'a', 3]
console.log(intersperse(['apple', 'banana', 'cherry'], ', ')); // ['apple', ', ', 'banana', ', ', 'cherry']