How to Delete a Value from an Array in JavaScript

Updated onbyAlan Morel
How to Delete a Value from an Array in JavaScript

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.

JAVASCRIPT
const 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.

JAVASCRIPT
const 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.

JAVASCRIPT
const 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.

JAVASCRIPT
const 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.

JAVASCRIPT
const 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.

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.