How to remove an element from an Array JavaScript ?

Last Updated On Monday 25th Apr 2022

javascript array remove element

  • JavaScript arrays allow you to group values and iterate over them.
  • You can add and remove array elements in different ways.

Removing an Element

Shift Method

To remove an element from the beginning of an array, we can use the shift method

	const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

days.shift(); // returns the removed element, in this case "Monday"

console.log(days); // [ 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ]
	

javascript remove element from array

Slice Method

There is also a way to remove the first element from an array without changing the underlying array ,We can use the slice method.

	const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

const newDays1 = days.slice(1);
const newDays2 = newDays1.slice(1);

console.log(newDays1); // [ 'Tuesday', 'Wednesday', 'Thursday', 'Friday' ]
console.log(newDays2); // [ 'Wednesday', 'Thursday', 'Friday' ]
	

As with other non-destructive methods, we need to assign the results to a new variable to save our changes

remove element from array javascript

slice is also handy if we know we want the last n elements of an array. pass it a negative index.(-)

	const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

const newDays1 = days.slice(-1);
const newDays2 = days.slice(-2);

console.log(newDays1); // [ 'Friday' ]
console.log(newDays2); // [ 'Thursday', 'Friday' ]
	

javascript remove item from array

From the End of an Array

  • To remove an element from the end of an array, we can use the pop method.
  • As with push, this method is destructive, it mutates the underlying array.
	const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

days.pop();

console.log(days); // [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday' ]
	

js remove from array

Splice Method

Removing an element from the middle of an array in JavaScript is a bit trickier than removing an element from the beginning or end.

	const alphabets = ['a', 'b', 'c', 'd', 'e'];

console.log(alphabets.splice(1)); // ['b','c','d','e']
	

array remove javascript

Remove From the Middle of an Array

We can use slice, combined with the spread operator, to make removing from the middle of an array much easier.

	const alphabets = ['a', 'b', 'c', 'd', 'e'];

console.log([...alphabets.slice(0, 2), ...alphabets.slice(3)]); // [ 'a', 'b', 'd', 'e' ]