Functional way to Insert a value between all the elements inside an array

  • A+

Let's say that I have the following array:

const myArray = ["q", "w", "e", "r", "t", "y"] 

What I would like to do is to add an element between all the elements, like this:

myArray.someMethod("XXX") // ["q", "XXX", "w", "XXX", "e", "XXX", "r", "XXX", "t", "XXX", "y"] 

In a way, it is kinda what .join does, but I would like the output to be another array, instead of a string.

I know how to do this with a loop, but I would like to know is the "functional" way to achieve this.


Instead an iterative approach, you could take a recursive approach by taking rest parameters and a check for the length of the rest array.

const     zip = ([a, ...r], v) => r.length ? [a, v,, v)] : [a];  console.log(zip(["q", "w", "e", "r", "t", "y"], 'XXX'));
.as-console-wrapper { max-height: 100% !important; top: 0; }


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: