There are various ways to remove an element from array. We will make use of
length to remove elements from array. Let’s discuss all the 5 methods one by one in brief.
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
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
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.
We can also remove and add new elements at the same time.
The splice method returns an array of deleted elements.
const numbers = [20, 40, 60, 80]; console.log(numbers.splice(1, 2)); // [40, 60]
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; console.log(games); // ['Cricket', 'Football', undefined]
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.
- 6 ways to add items to an array
Thanks for you time
Find more web development blogs on jscurious.com