How to Remove Element from Array in JavaScript: Simple Methods
To remove an element from an array in JavaScript, you can use
splice() to remove by index, or filter() to remove by value. For example, array.splice(index, 1) removes one element at the specified index.Syntax
splice(index, count): Removes count elements starting from index in the array.
filter(callback): Creates a new array with elements that pass the test in callback.
pop(): Removes the last element from the array.
javascript
array.splice(index, 1);
array = array.filter(element => element !== value);
array.pop();Example
This example shows how to remove an element by index using splice() and by value using filter().
javascript
const fruits = ['apple', 'banana', 'cherry', 'date']; // Remove 'banana' by index (1) fruits.splice(1, 1); console.log(fruits); // ['apple', 'cherry', 'date'] // Remove 'date' by value const filteredFruits = fruits.filter(fruit => fruit !== 'date'); console.log(filteredFruits); // ['apple', 'cherry']
Output
['apple', 'cherry', 'date']
['apple', 'cherry']
Common Pitfalls
One common mistake is trying to remove an element by value using splice() without knowing its index. Another is modifying the array inside a loop incorrectly, which can skip elements.
Also, filter() returns a new array and does not change the original array.
javascript
const numbers = [1, 2, 3, 4]; // Wrong: splice with value instead of index // numbers.splice(3, 1); // removes element at index 3, not value 3 // Right: find index first const index = numbers.indexOf(3); if (index !== -1) { numbers.splice(index, 1); } console.log(numbers); // [1, 2, 4]
Output
[1, 2, 4]
Quick Reference
| Method | Description | Modifies Original Array? |
|---|---|---|
| splice(index, count) | Removes elements by index | Yes |
| filter(callback) | Removes elements by condition, returns new array | No |
| pop() | Removes last element | Yes |
| shift() | Removes first element | Yes |
Key Takeaways
Use splice() to remove elements by their index in the array.
Use filter() to remove elements by value or condition, which returns a new array.
Remember splice() changes the original array, filter() does not.
Always find the index before using splice() to remove by value.
pop() and shift() remove elements from the ends of the array.