Skip to content Skip to sidebar Skip to footer

How To Insert A New Element At Any Position 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

Solution 1:

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);

Solution 2:

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)

Solution 3:

You can use map() with ES6 spread syntax and concat()

var arr = ['a', 'b', 'c']
var newArr = [0].concat(...arr.map(e => [e, 0]))

console.log(newArr)

Solution 4:

Another way:

var a = ['a', 'b', 'c'],
  b;

b = a.reduce((arr, b) => [...arr, b, 0], []);

console.log(b);

Solution 5:

Another ES6+ version using flatmap (if creation of a new array instead is ok):

['a', 'b', 'c', 'd']
    .flatMap((e, index) => index ? [e, 0] : [0, e, 0])

Post a Comment for "How To Insert A New Element At Any Position Of A Js Array?"