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.
Getting Started with TypeScript
Managing PHP Dependencies with Composer
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
Best Visual Studio Code Extensions for 2022
How to deploy a PHP app using Docker
Getting Started with Sass
Using Puppeteer and Jest for End-to-End Testing
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with React
How To Create a Modal Popup Box with CSS and JavaScript
