# Array Inject

**URL:** <https://es.discourse.group/t/array-inject/222>\
**Category:** 💡 Ideas\
**Created:** [February 14, 2020, 6:57pm UTC](https://es.discourse.group/t/array-inject/222 "2020-02-14T18:57:43Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![RoyTouw](https://avatars.discourse-cdn.com/v4/letter/r/c37758/32.png) [@RoyTouw](https://es.discourse.group/u/RoyTouw)\
**Post date:** [February 14, 2020, 6:57pm UTC](https://es.discourse.group/t/array-inject/222/1 "2020-02-14T18:57:43Z")

</div>

Today I had to create a function which added one element after every single element in an array. E.g.  
['a', 'a', 'a'] =\> ['a', 'b', 'a', 'b', 'a', 'b']

Because of the nice array methods like map, and filter and such I searched for a similar method for injecting elements accepting an arrow function but I couldn't find one. I thought an inject method might be a nice addition following this pattern:  
[1,2,3].inject(el =\> el \> 2, el =\> el += 2);

The first parameter being a boolean function to see where to inject a new element, and the second parameter being or returning a value to inject in that position giving the result:  
[1,2,3,5,4,6]

Like map it wouldn't mutate the original array but instead return a new one.  
I'd like to hear what other people think of this idea.

---

<div class="post-metadata">

**Author:** ![bergus](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/bergus/32/152_2.png) [@bergus](https://es.discourse.group/u/bergus)\
**Post date:** [February 14, 2020, 9:20pm UTC](https://es.discourse.group/t/array-inject/222/2 "2020-02-14T21:20:15Z")

</div>

Hello Roy!

The more generic abstraction over `map` and `filter` would be [`flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap). With that, you can easily achieve the results you're looking for:

```javascript
['a', 'a', 'a'].flatMap(x => [x, 'b'])

[1,2,3,4].flatMap(el => el>2 ? [el, el+2] : [el])

```

---

<div class="post-metadata">

**Author:** ![RoyTouw](https://avatars.discourse-cdn.com/v4/letter/r/c37758/32.png) [@RoyTouw](https://es.discourse.group/u/RoyTouw)\
**Post date:** [February 15, 2020, 7:17pm UTC](https://es.discourse.group/t/array-inject/222/3 "2020-02-15T19:17:58Z")

</div>

Oh cool, I didn't know flatMap was used for this, i will rewrite my function using this method thank you!

---

<div class="post-metadata">

**Author:** ![mnini](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/mnini/32/253_2.png) [@mnini](https://es.discourse.group/u/mnini)\
**Post date:** [February 22, 2020, 2:26am UTC](https://es.discourse.group/t/array-inject/222/4 "2020-02-22T02:26:50Z")

</div>

```javascript
while(element = array.pop()){
      array0.push(element)
      array0.push(elementAfterEachElementInArray)
}

```
