How to Remove an Element from an Array in Javascript

0 min read 192 words

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]
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts