How to Delete a Value from an Array in JavaScript
Table of Contents
In this post, we'll learn how to delete a value from an array. This is a question that comes up often in JavaScript because of how often it needs to be done.
There are three ways to delete a value from an array: splice()
, pop()
, and shift()
.
splice()
The best way to remove an element from an array is using the splice()
method. Pass it the index of the element you want to remove and the number of elements you want to remove.
JAVASCRIPTconst array = ["apple", "banana", "orange", "pineapple"];
const index = 2;
array.splice(index, 1);
console.log(array);
BASH(3) ['apple', 'banana', 'pineapple']
You need to know the index of the element you want to remove. If you want to remove an element from an array by value, you can use .indexOf()
to find it.
JAVASCRIPTconst array = ["apple", "banana", "orange", "pineapple"];
const index = array.indexOf("banana");
array.splice(index, 1);
console.log(array);
BASH(3) ['apple', 'orange', 'pineapple']
shift()
You can use the shift()
method to remove the first element of an array.
JAVASCRIPTconst array = ["apple", "banana", "orange", "pineapple"];
array.shift();
console.log(array);
BASH(3) ['banana', 'orange', 'pineapple']
pop()
You can use the pop()
method to remove the last element of an array.
JAVASCRIPTconst array = ["apple", "banana", "orange", "pineapple"];
array.pop();
console.log(array);
BASH(3) ['apple', 'banana', 'orange']
delete
You can also use the delete
keyword to remove an element from an array. Keep in mind that this will create a sparse array. This means that the array will have a hole in it.
JAVASCRIPTconst array = ["apple", "banana", "orange", "pineapple"];
delete array[2];
console.log(array);
console.log(array.length);
BASH(4) ['apple', 'banana', empty, 'pineapple']
4
As you can see, the 3rd element is now empty, however the length of the array is still 4. This is why using delete
is not a recommended way to remove an element from an array.
Conclusion
Hopefully this post has covered all the ways to remove an element from an array. As a summary, use splice()
to remove an element, use shift()
to remove the first element, use pop()
to remove the last element. Don't use delete
to remove an element from an array unless you understand the consequences.
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript