Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to insert objects between array elements?

I'm sure there are many ways to achieve that but I'm looking for something "elegant".

a = [   'a',   'b',   'c' ];  magicArrayJoin(a, {value: 255} ); // insert the same object between each item  result ==  [   'a',   {value: 255},   'b',   {value: 255}   'c' ]; 

All proposals are welcome. :)

like image 751
cimak Avatar asked Aug 07 '15 14:08

cimak


People also ask

Which are the methods to insert elements into the array?

The logic used to insert element is − for(i=size-1;i>=pos-1;i--) student[i+1]=student[i]; student[pos-1]= value; Final array should be printed using for loop.

Which method is used to add new element to an array of objects?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed.

How do you add elements to the middle of an array?

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 function do you use to insert one or more elements to the end of an array?

The push() method adds one or more elements to the end of an array and returns the new length of the array.


1 Answers

You can do it with flatMap. It can be found from lodash for example

_.flatMap([1,2,3,4], (value, index, array) =>      array.length -1 !== index // check for the last item      ? [value, "s"]      : value ); 

ouputs

[1, "s", 2, "s", 3, "s", 4] 

Update

Array#flatMap proposal is in the works so in future this should work:

[1, 2, 3, 4].flatMap(     (value, index, array) =>         array.length - 1 !== index // check for the last item             ? [value, "s"]             : value, ); 
like image 151
Epeli Avatar answered Oct 07 '22 12:10

Epeli