There are several ways to remove an element from an array in JavaScript:
const arr = [1, 2, 3, 4, 5];
// Remove last
arr.pop(); // [1, 2, 3, 4]
// Remove first
arr.shift(); // [2, 3, 4]
// Remove by index
arr.splice(1, 1); // [2, 4]
// Create new without element
const filtered = arr.filter(x => x !== 2); // [4]Removing an element from an array is like taking an item out of a box. There are different tools for this! 📦🔧
Simplest way — remove the last item from the box:
const fruits = ['apple', 'banana', 'orange'];
// Remove last element
const last = fruits.pop(); // Returns 'orange'
console.log(fruits); // ['apple', 'banana']
console.log(last); // 'orange'Removes the first item from the box:
const fruits = ['apple', 'banana', 'orange'];
// Remove first element
const first = fruits.shift(); // Returns 'apple'
console.log(fruits); // ['banana', 'orange']
console.log(first); // 'apple'Like a surgical scalpel — you can remove any element:
const fruits = ['apple', 'banana', 'orange', 'pear'];
// Remove one element at index 1
fruits.splice(1, 1); // Removes 'banana'
console.log(fruits); // ['apple', 'orange', 'pear']
// Remove several elements
fruits.splice(0, 2); // Removes 'apple' and 'orange'
console.log(fruits); // ['pear']Creates a new box without needed items:
const numbers = [1, 2, 3, 4, 5];
// Create new array without twos
const filtered = numbers.filter(x => x !== 2);
console.log(numbers); // [1, 2, 3, 4, 5] — original unchanged
console.log(filtered); // [1, 3, 4, 5] — new arrayThere’s also [delete], but you shouldn’t use it:
const arr = [1, 2, 3];
delete arr[1]; // Don't do this!
console.log(arr); // [1, empty, 3] — hole in array!// ✅ When you need to remove from edges
const stack = [1, 2, 3];
stack.pop(); // Remove from end — stack
stack.shift(); // Remove from start — queue// ✅ When you need to remove by index
const arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // Remove element at index 2// ✅ When you need to remove by condition
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(x => x % 2 === 0); // [2, 4]// ❌ Bad — creates holes
const arr = [1, 2, 3];
delete arr[1];
console.log(arr); // [1, empty, 3]
// ✅ Good — use splice
const arr2 = [1, 2, 3];
arr2.splice(1, 1);
console.log(arr2); // [1, 3]// ❌ Mistake — think filter modifies array
const arr = [1, 2, 3];
arr.filter(x => x !== 2); // Doesn't modify arr!
// ✅ Correct — save result
const newArr = arr.filter(x => x !== 2);Knowing different removal methods helps choose the right tool for each task! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪