Computer >> Computer tutorials >  >> Programming >> Javascript

Adding an element at a given position of the array in Javascript


Sometimes you need to add an element to a given position in an array. JavaScript doesn't support it out of the box. So we need to create a function to be able to do that. We can add it to the Array prototype so that we can use it directly on the object.

Example

Array.prototype.insert = function(data, position) {
   if (position >= this.length) {
      this.push(data) // Put at the end if position is more than total length of array
   } else if (position <= 0) {
      this.unshift(data) // Put at the start if position is less than or equal to 0
   } else { // Shift all elements to right
      for (let i = this.length; i >= position; i--) {
         this[i] = this[i - 1];
      }
      this[position] = data;
   }
}

let arr = [1, 2, 3, 4];
arr.insert(-1, 2);
console.log(arr);

Output

This will give the output −

[1, 2, -1, 3, 4]

Now the insert method is available on every array object you create.

You can also use the splice method to insert elements at given positions. For example,

Example

var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);

Output

This will give the output −

['Jan', 'Feb', 'March', 'April', 'June']

The first argument of the method is the index we want to remove elements from or insert elements into. The second argument is the number of elements we want to remove. And the third argument onwards are the values we would like to insert into the array.