Skip to content

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"]
Code language: JavaScript (javascript)

Example 2 using splice:

var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // Remove Sunday -- index 0 and Monday -- index 1 myArray.splice(,2)
Code language: JavaScript (javascript)

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))
Code language: JavaScript (javascript)

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']
Code language: JavaScript (javascript)

Option 4 – Use remove to remove an element

array.remove(number);
Code language: JavaScript (javascript)

Option 5 – Change length to remove elements

var arr = [1, 2, 3, 4, 5, 6]; arr.length = 4; // [1, 2, 3, 4]
Code language: JavaScript (javascript)

See also  jQuery Colorbox not showing but background shows
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x