I have an array [a, b, c]
. I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0]
.
I guess it would be something like this, but I can't make it works.
for (let i = 0; i < array.length; i++) { newArray = [ ...array.splice(0, i), 0, ...array.splice(i, array.length), ]; }
Thank you for helping me!
Example 1: Add Item to Array Using splice() In the splice() method, The first argument specifies the index where you want to insert an item. The second argument (here 0) specifies the number of items to remove. The third argument specifies the element that you want to add to an array.
You want to explicitly add it at a particular place of the array. That place is called the index. Array indexes start from 0 , so if you want to add the item first, you'll use index 0 , in the second place the index is 1 , and so on. To perform this operation you will use the splice() method of an array.
We can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array. After inserting the element in the array, the positions or index location is increased but it does not mean the size of the array is increasing.
Using array_push() function – This function is used to push new elements into an array.
Another way if you want to exclude the start and end of array is :
var arr = ['a', 'b', 'c'] var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b)) console.log(newArr)
For getting a new array, you could concat the part an add a zero element for each element.
var array = ['a', 'b', 'c'], result = array.reduce((r, a) => r.concat(a, 0), [0]); console.log(result);
Using the same array
var array = ['a', 'b', 'c'], i = 0; while (i <= array.length) { array.splice(i, 0, 0); i += 2; } console.log(array);
A bit shorter with iterating from the end.
var array = ['a', 'b', 'c'], i = array.length; do { array.splice(i, 0, 0); } while (i--) console.log(array);
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