Say I have an array var arr = [1, 2, 3]
, and I want to separate each element by an element eg. var sep = \"&\"
, so the output is [1, \"&a
You could use Array.from
to create an array with the final size, and then use the callback argument to actually populate it:
const intersperse = (arr, sep) => Array.from(
{ length: Math.max(0, arr.length * 2 - 1) },
(_, i) => i % 2 ? sep : arr[i >> 1]
);
// Demo:
let res = intersperse([1, 2, 3], "&");
console.log(res);