There are various ways to remove an element from array. We will make use of pop
, shift
, splice
, delete
and length
to remove elements from array. Let’s discuss all the 5 methods one by one in brief.
The pop() method
This method removes an element from the end of array. It returns the value that was removed.
const countries = ['India', 'US', 'Canada', 'France'];
const removedItem = countries.pop();
console.log(countries); // ['India', 'US', 'Canada']
console.log(removedItem); // France
The shift() method
This method removes an element from the beginning of array and returns the removed element.
const phones = ['Nokia', 'Samsung', 'Apple'];
const removedItem = phones.shift();
console.log(phones); // ['Samsung', 'Apple']
console.log(removedItem); // Nokia
The splice() method
This method can both remove and add elements at a specified index of array.
- The first parameter of
splice()
takes an array index where you want to add or remove element. - The second parameter takes number of elements to be removed from the specified index. If not removing any element then this can be 0.
- The third parameter takes elements to be added at the specified index. If we are only removing then this can be left as blank. We can add as many values as we want.
const language = ['JavaScript', 'Java', 'SQL', '.NET'];
language.splice(2, 1);
console.log(language); //['JavaScript', 'Java', '.NET']
We can also remove and add new elements at the same time.
const language = ['JavaScript', 'Java', 'SQL', '.NET'];
language.splice(2, 2, 'Android', 'Swift');
console.log(language); //['JavaScript', 'Java', 'Android', 'Swift']
The splice method returns an array of deleted elements.
const numbers = [20, 40, 60, 80];
console.log(numbers.splice(1, 2)); // [40, 60]
The delete keyword
The delete
keyword is used to delete a property of an object. This can be used to delete any element from array. The delete
keyword deletes the element but leaves an undefined value at that place.
const games = ['Cricket', 'Football', 'Hockey'];
delete games[2];
console.log(games); // ['Cricket', 'Football', undefined]
Using Array length
If we want to remove some specified number of elements from the end of an array, then we can just set the array’s length
property to original length of array subtracted by the number of elements to be removed.
const numbers = [10, 20, 30, 40, 50];
numbers.length = 3; // to remove two elements from end
console.log(numbers); // [10, 20, 30]
We have discussed 5 different methods to remove elements from an array. You can use any of the method based on your requirements.
You May Also Like
- 6 ways to add items to an array
- 6 ways to find items in an Array in JavaScript
- 20 JavaScript Shorthand Techniques that will save your time
Thanks for you time
Find more web development blogs on jscurious.com
Top comments (0)