Adding an element in an array using Javascript

HTMLJavascriptProgramming Scripts

Adding an element to an array can be done using different functions for different positions.

Adding an element at the end of the array

This can be accomplished using the push method. For example,

let veggies = ["Onion", "Raddish"];
veggies.push("Cabbage");
console.log(veggies);

This will give the output −

["Onion", "Raddish", "Cabbage"]

You can also use this to push multiple items at the same time as it supports a variable number of

arguments. For example,

let veggies = ["Onion", "Raddish"];
veggies.push("Cabbage", "Carrot", "Broccoli");
console.log(veggies);

This will give the output −

["Onion", "Raddish", "Cabbage", "Carrot", "Broccoli"]

Adding an element at the start of the array

This can be accomplished using the unshift method. For example,

let veggies = ["Onion", "Raddish"];
veggies.unshift("Cabbage");
console.log(veggies);

This will give the output −

["Cabbage", "Onion", "Raddish"]

You can also use this to unshift multiple items at the same time as it supports a variable number of

arguments. For example,

let veggies = ["Onion", "Raddish"];
veggies.unshift("Cabbage", "Carrot", "Broccoli");
console.log(veggies);

This will give the output −

["Cabbage", "Carrot", "Broccoli", "Onion", "Raddish"]

Adding an element at a given position of the array

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.

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

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,

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

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.

raja
Published on 06-Jul-2018 09:54:28
Advertisements