How do I remove a particular element from and array in JavaScript?

Snippets Of JavaScript

You can remove elements in several different ways:

  • splice - removes an element from a specific array index
  • pop - removes an element from the end of an array
  • shift - removes an element from the start of an array
  • filter - allows you to remove elements from an array by creating a new array and filtering only the elements you want

splice()

splice() removes an element from a specific array index (with the index starting at zero). The first parameter for splice() of the item to remove, the second is the number of items to remove. A third parameter allows items to be added to the array from the index position.

const array = ["Jan","Feb","Mar","Apr","May","Jun","Jly"];
const index = array.indexOf('Apr');

// only splice array when item is found
if (index > -1) { 
  array.splice(index, 1);
}

/// Output the result
array;

/// expected result: ["Jan","Feb","Mar","May","Jun","Jly"]
                

pop()

pop() removes an element from the end of an array.

const array = ["Jan","Feb","Mar","Apr","May","Jun","Jly"];
const removedElement = array.pop();

/// Output the result
array;
/// expected result: ["Jan","Feb","Mar","Apr","May","Jun"]
                  

shift()

find() returns the first element for which the supplied function returns true.

const array = ["Jan","Feb","Mar","Apr","May","Jun","Jly"];
const removedElement = array.shift();

/// Output the result
array;
/// expected result: ["Feb","Mar","Apr","May","Jun","Jly"]
                

filter()

filter() creates a new array using filter function that keeps only those elements that return true.. The result is a new array containing a subset of the elements from the supplied array.

const array = ["Jan","Feb","Mar","Apr","May","Jun","Jly"];
const newArray = array.filter(month => month !== 'Apr');

/// Output the result
newArray;

/// expected result: ["Jan","Feb","Mar","May","Jun","Jly"]