Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 853
Enrique Moreno Tent Avatar asked Jan 15 '19 12:01

Enrique Moreno Tent


2 Answers

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; }
like image 74
Nina Scholz Avatar answered Sep 29 '22 06:09

Nina Scholz


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"]
like image 36
TaoPR Avatar answered Sep 29 '22 06:09

TaoPR