js delete item from array

How to Delete an Item from Array in JavaScript

If you are working with arrays in JavaScript, at some point, you may need to remove an item from it. There are multiple ways to do so. Let's explore them one by one.

Using the splice() method

The easiest way to remove an item from an array is by using the splice() method. This method changes the content of an array by removing or replacing existing elements and/or adding new elements in place.

To remove an item at a specific index, you need to pass two arguments to the splice() method: the index at which to start changing the array, and the number of elements to remove.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
fruits.splice(2, 1);
console.log(fruits); // Output: ['apple', 'banana', 'kiwi']

In the above example, we have removed the item at index 2 (i.e., 'orange') from the fruits array using the splice() method.

Using the filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. So, to remove an item from an array using this method, we need to create a new array that excludes the item we want to remove.

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

In the above example, we have created a new array called filteredFruits by filtering out the item 'orange' from the original fruits array using the filter() method.

Using the pop() or shift() method

If you want to remove the last or first item from an array, you can use the pop() or shift() method, respectively. The pop() method removes the last element from an array and returns that element, while the shift() method removes the first element from an array and returns that element.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
console.log(fruits); // Output: ['apple', 'banana', 'orange']

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
console.log(fruits); // Output: ['banana', 'orange', 'kiwi']

In the above examples, we have used the pop() method to remove the last item ('kiwi') and the shift() method to remove the first item ('apple') from the fruits array.

These are some of the ways to remove an item from an array in JavaScript. Choose the method that suits your needs and coding style. Happy coding!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]