Arrays in JavaScript allow you to group values together and iterate over them. You can add and remove elements from the array in different ways. Unfortunately, there is no simple method like Array.remove()
that works for all cases.
So how do you delete an element from an array in Javascript?
Here we will discuss three different ways to solve this problem once and for all.
Javascript already has a method to handle this, the pop()
method.
It removes the last element from the array, returns that element, and updates the length property.
The pop()
method modifies the array on which it is invoked, which means that the last element is removed completely and the length of the array is reduced without generating a new array.
let arr = ['🍉', '🍎', '🍐', '🍆', '🍋', '🍌'];
console.log(arr.pop()); // 🍌
console.log(arr); // [ '🍉', '🍎', '🍐', '🍆', '🍋' ]
How to remove the first element from a JavaScript array? Easy…
Using the shift()
method. This works much like the pop()
method we just saw, except that it removes the first element of a Javascript array instead of the last element.
This method takes no parameters, since its only function is to remove the first element of an array. When the element is removed, the remaining elements are moved. This means that the array index is updated, and you don’t lose the first reference (arr[0]
).
It is worth remembering that this method modifies the array on which it is invoked. Also, the shift()
method returns the element that was removed and updates the length property.
If there are no elements, or the array length is 0, the method returns undefined
.
let arr = ['🍉', '🍎', '🍐', '🍆', '🍋', '🍌'];
console.log(arr.shift()); // 🍉
console.log(arr); // ["🍎", "🍐", "🍆", "🍋", "🍌"]
The splice()
method can be used to add or remove elements from an array. Only the first argument is required.
In the example below, we will use the splice()
method to remove 1 element starting at position [2]
.
let arr = ['🍉', '🍎', '🍐', '🍆', '🍋', '🍌'];
console.log(arr.splice(2,1)); // 🍐
console.log(arr); // ["🍉", "🍎", "🍆", "🍋", "🍌"]
I find it easier to visualise what I am going to remove by thinking in the following way:
“Starting at index position [2], remove one element [ “🍐” ] and keep the rest [“🍉”, “🍎”, “🍆”, “🍋”, “🍌”].”
With these three methods you can already solve many problems.
See you next time!
You actually make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand. It seems too complicated and very broad for me. I'm looking forward for your next post, I’ll try to get the hang of it!
Very good info. Lucky me I ran across your blog by accident (stumbleupon). I've book-marked it for later!
Leave a Reply