Onjsdev

Share


How to Remove Elements in an Array in JavaScript


By onjsdev

Dec 5th, 2023

Arrays are fundamental data structures in JavaScript, and manipulating them is a common task in web development.

Whether you want to remove specific elements or trim the array, this guide will walk you through the basics.

Removing Elements by Index

Using splice()

The splice() method allows you to add or remove elements from a specific index in an array. To remove elements, specify the index and the number of elements to delete.

let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.splice(1, 2); // Removes 2 elements starting from index 1
console.log(fruits); // Output: ['apple', 'grape']

Using slice()

The slice() method doesn't modify the original array but returns a new array with the specified elements removed.

let fruits = ['apple', 'banana', 'orange', 'grape'];
let newArray = fruits.slice(0, 1).concat(fruits.slice(2));
console.log(newArray); // Output: ['apple', 'orange', 'grape']

Removing Elements by Value

Using filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function. Use it to exclude elements based on their values.

let fruits = ['apple', 'banana', 'orange', 'grape'];
let filteredFruits = fruits.filter(fruit => fruit !== 'banana');
console.log(filteredFruits); // Output: ['apple', 'orange', 'grape']

Removing the Last Element

Using pop()

The pop() method removes the last element from an array and returns that element.

let fruits = ['apple', 'banana', 'orange', 'grape'];
fruits.pop();
console.log(fruits); // Output: ['apple', 'banana', 'orange']

Conclusion

In this article, we have covered different techniques to remove elements from an array in JavaScript. Experiment with these methods to get comfortable with array manipulation

Thank you for reading.