Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 258
Philippe Avatar asked Oct 02 '17 15:10

Philippe


People also ask

How do you insert an element in an array at a given position in JavaScript?

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.

How can we add elements at any specific position in JS?

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.

Can we insert an element at a specific position in 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.

What function is used to add a new element at any position in an array?

Using array_push() function – This function is used to push new elements into an array.


2 Answers

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)
like image 34
Vincent Menant Avatar answered Sep 22 '22 11:09

Vincent Menant


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);
like image 159
Nina Scholz Avatar answered Sep 21 '22 11:09

Nina Scholz