Removing Elements from an Array with Javascript

javascript
Published on June 25, 2019

Removing the First Element

The shift() method can be used to remove the first element of the array.

Return value : The element that was removed.

var arr = [1, 2, 3, 4, 5];

var removed = arr.shift();

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

// 1
console.log(removed);

Removing the Last Element

The pop() method removes the last element of the array.

Return value : The element that was removed.

var arr = [1, 2, 3, 4, 5];

var removed = arr.pop();

// [1, 2, 3, 4]
console.log(arr);

// 5
console.log(removed);

Removing Element from a Given Position

To remove an element from any given position, the splice() method can be used. The splice() modifies an array — it can add new elements or delete elements. In this case we will focus on deleting elements.

You need to pass 2 parameters to splice() :

  • First parameter represents the position from where we want to start deleting elements. Position works like the index of the array, however negative values are also allowed.

    With a negative value, the starting position is set from the end position of the array. For example -1 would mean to delete elements starting from the last position. -2 would mean to delete elements starting from the second-last position.

  • The second parameter represents how many elements are to be deleted, starting from the given position.

Return value : An array of all elements that were deleted.

Example 1 - Remove 3 elements starting from the second element :

var arr = [1, 2, 3, 4, 5, 6];

var removed = arr.splice(1, 3);

// [1, 5, 6]
console.log(arr);

// [2, 3, 4]
console.log(removed);

Example 2 - Remove the first element :

var arr = [1, 2, 3, 4, 5, 6];

var removed = arr.splice(0, 1);

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

// [1]
console.log(removed);

Example 3 - Remove the last element :

var arr = [1, 2, 3, 4, 5, 6];

var removed = arr.splice(-1, 1);

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

// [6]
console.log(removed);

Example 4 - Remove the last 2 elements :

var arr = [1, 2, 3, 4, 5, 6];

var removed = arr.splice(-2, 2);

// [1, 2, 3, 4]
console.log(arr);

// [5, 6]
console.log(removed);
In this Tutorial