How to Remove an Element From an Array in Javascript

If you need to remove an element from an array in Javascript, then you can use one of the following five (5) options:

Option 1 – Use splice to remove an element

Example 1 using splice:

var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car");
colors.splice(carIndex, 1);

// colors = ["red","blue","green"]

Example 2 using splice:

var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// Remove Sunday -- index 0 and Monday -- index 1
myArray.splice(0,2)

Option 2 – Use filter to remove an element

var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let itemToBeRemoved = ["Sunday", "Monday"]
var filteredArray = myArray.filter(item => !itemToBeRemoved.includes(item))

Option 3 – Use pop to remove an element

let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']

// remove the last element from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();

// get removed element
console.log(removedElement); // 'sleep'
console.log(dailyActivities);  // ['work', 'eat']

Option 4 – Use remove to remove an element

array.remove(number);

Option 5 – Change length to remove elements

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

arr.length = 4;

// [1, 2, 3, 4]