Array.prototype.reduce()
to combine elements into a string.separator
, to use a default separator of ','
.end
, to use the same value as separator
by default.
const join = (arr, separator = ',', end = separator) =>
arr.reduce(
(acc, val, i) =>
i === arr.length - 2
? acc + val + end
: i === arr.length - 1
? acc + val
: acc + val + separator,
''
);
join(['pen', 'pineapple', 'apple', 'pen'],',','&'); // 'pen,pineapple,apple&pen' join(['pen', 'pineapple', 'apple', 'pen'], ','); // 'pen,pineapple,apple,pen' join(['pen', 'pineapple', 'apple', 'pen']); // 'pen,pineapple,apple,pen'
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️