Philippe Philippe - 1 year ago 148
Javascript Question

How to insert a new element in between all elements of a JS array?

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!

Answer Source

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 iteratimg from the end.

var array = ['a', 'b', 'c'],
    i = array.length;

do {
    array.splice(i, 0, 0);
} while (i--)

console.log(array);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download