Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Which method facilitates to combine all the array elements into a string in JavaScript?

Use the JavaScript Array join() method to concatenate all elements of an array into a string separated by a separator.

How do you add an element in the middle of an array in JavaScript?

Adding Elements to the Middle JavaScript arrays have a push() function that lets you add elements to the end of the array, and an unshift() function that lets you add elements to the beginning of the array. The splice() function is the only native array function that lets you add elements to the middle of an array.

Which method of an array removes the element from the end in JavaScript?

The pop() method in JavaScript is used to remove the last element from the 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)

A spread and explicit return in reducing function will make it more terse:

const intersperse = (arr, sep) => arr.reduce((a,v)=>[...a,v,sep],[]).slice(0,-1)
// intersperse([1,2,3], 'z')
// [1, "z", 2, "z", 3]

In ES6, you'd write a generator function that can produce an iterator which yields the input with the interspersed elements:

function* intersperse(iterable, separator) {
    const iterator = iterable[Symbol.iterator]();
    const first = iterator.next();
    if (first.done) return;
    else yield first.value;
    for (const value of iterator) {
        yield separator;
        yield value;
    }
}

console.log(Array.from(intersperse([1, 2, 3], "&")));

One straightforward approach could be like feeding the reduce function with an initial array in size one less than the double of our original array, filled with the character to be used for interspersing. Then mapping the elements of the original array at index i to 2*i in the initially fed target array would do the job perfectly..

In this approach i don't see (m)any redundant operations. Also since we are not modifying any of the array sizes after they are set, i wouldn't expect any background tasks to run for memory reallocation, optimization etc. One other good part is using the standard array methods since they check all kinds of mismatch and whatnot.

This function returns a new array, in which the called upon array's items are interspersed with the provided argument.

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Array.prototype.intersperse = function(s){
  return this.reduce((p,c,i) => (p[2*i]=c,p), new Array(2*this.length-1).fill(s));
}
document.write("<pre>" + JSON.stringify(arr.intersperse("&")) + "</pre>");

Using reduce but without slice

var arr = ['a','b','c','d'];
var lastIndex = arr.length-1;
arr.reduce((res,x,index)=>{
   res.push(x);
   if(lastIndex !== index)
    res.push('&');
  return res;
},[]);

javascript has a method join() and split()

var arr = ['a','b','c','d'];
arr = arr.join('&');
document.writeln(arr);

Output should be: a&b&c&d

now split again:

arr = arr.split("");

arr is now:

arr = ['a','&','b','&','c','&','d'];

If you have Ramda in your dependencies or if willing to add it, there is intersperse method there.

From the docs:

Creates a new list with the separator interposed between elements.

Dispatches to the intersperse method of the second argument, if present.

R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']

Or you can check out the source for one of the ways to do it in your codebase. https://github.com/ramda/ramda/blob/v0.24.1/src/intersperse.js