Inserting elements in JavaScript Array

June 20, 2020

Conside we have an array

let arr = [3,4,5];

Append elements to an array using push

To add elements to the end of the array you can use push method. The push method will return length of the array.

arr.push(6); //4
console.log(arr); // [3,4,5,6]

arr.push(7,8); // 6
console.log(arr); // [3,4,5,6,7,8]

Prepend elements to an array using unshift

To add elements to the beginning of the array you can use unshift method. The unshift method will return length of the array

arr.unshift(2); //7
console.log(arr); // [2,3,4,5,6,7,8]

console.log(arr); // [0,1,2,3,4,5,6,7,8]

Insert elements to an specific index of an array using splice

To insert an element to a specific index we don't have any in-build method so we can use splice method.

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements, in the original array(which means the source array is modified)

splice method takes three argument

  • start → The index at which to start changing the array.
  • deleteCount(optional) → An integer indicating the number of elements in the array to remove from start.
  • elem1, elem2 … → The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.

In order to insert an element to the specific index , we need to provide arguments as

  • start → index where to insert the element
  • deleteCount → 0 (because we don’t need to delete element)
  • elem → elements to insert
function insertAt(array, index, ...elements) {
    array.splice(index, 0, ...elements);

Conside we have an array

var num = [1,2,4];

In the num array , conside we need to insert 3 in the 2nd index for that

insertAt(num, 2, 3); // [1,2,3,4]
// insert multiple elements

insertAt(num, 2, -1,-2,-3); //this will insert 3 elements starting from index 2

Please donate here, for making more tutorials.