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. :)
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.
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.
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.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
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]
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, );
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