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 of 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, ...zip(r, v)] : [a];
console.log(zip(["q", "w", "e", "r", "t", "y"], 'XXX'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
In a functional programming way, an Array is a Monad which means it is flatMappable. FlatMap is an implementation of a Monadic bind operator which for an Array it maps an element to a new array and flatten them together.
With this idea, you just need to add a new value to the output array inside the flatMap function. See following
Array.prototype.someMethod = function(a){ return this.flatMap(i => [i,a]) }
myArray.someMethod("XXX")
// Array(12) [ "q", "XXX", "w", "XXX", "e", "XXX", "r", "XXX", "t", "XXX", … ]
The above example adds the XXX at the end of the Array, so we can ignore the last element from being padded by making use of the index argument of the flatMap as follows
Array.prototype.someMethod = function(a){ let L=this.length; return this.flatMap((n,i) => (i<L-1) ? [n,a] : [n]) }
myArray.someMethod("XXX")
// Array(11) [ "q", "XXX", "w", "XXX", "e", "XXX", "r", "XXX", "t", "XXX", "y"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With