Terse way to intersperse element between all elements in JavaScript array?

Using a generator:

function *intersperse(a, delim) {
  let first = true;
  for (const x of a) {
    if (!first) yield delim;
    first = false;
    yield x;
  }
}

console.log([...intersperse(array, '&')]);

Thanks to @Bergi for pointing out the useful generalization that the input could be any iterable.

If you don’t like using generators, then

[].concat(...a.map(e => ['&', e])).slice(1)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)