Remove item from array in Javascript
In this post, we are going to learn to remove one or multiple elements from an array using Javascript.
const myArray = [2, 5, 9];
const removeIndex = 2;
myArray.splice(removeIndex, 1);
console.log(myArray);
Output
Remove array items using .splice() function
We can easily remove array elements using Array.splice() function in javascript. It takes two arguments as a parameter. The first argument is the index or position of the element in the array from where you want to start removing the element. The second argument is the number of items that you want to remove.
Syntax
Array.splice(item_index, number_of_items)
Code Example 1 - Remove a single element
let arr = ["a", "b", "c", "d", "e"];
arr.splice(2, 1);
console.log(arr);
Output
["a","b","d","e"]
Live Demo for above code example
Code Example 2 - Remove multiple items using splice() function
let arr = ["a", "b", "c", "d", "e"];
arr.splice(2, 3);
console.log(arr);
Output
["a","b"]
We are removing 3 items from an array using the above code example.
Live Demo for above code example
Get item index and remove it from the array
We are using the indexOf() function here to get the index of the item from the array and the splice() function to remove that item.
const arr = ['a', 'b', 'c', 'd', 'e'];
const item_index = arr.indexOf('c');
if (item_index > -1) {
arr.splice(item_index, 1);
}
console.log(arr);
Output
["a","b","d","e"]
Remove first item from an array - shift() function
You can use the shift() function in Javascript to delete the very first element from an array. The Array.shift() function returns the first element from the array along with deleting the element.
Syntax
Array.shift()
Code example
let arr = [10, 20, 30, 40, 50];
arr.shift();
console.log(arr);
Output
[20,30,40,50]
Remove last item from array - pop() function
We can remove the last element from the array using Array.pop() function. It will also return the last element from the array.
Syntax
Array.pop()
Code Example
let arr = [10, 20, 30, 40, 50];
arr.pop();
console.log(arr);
Output
[10,20,30,40]
Remove items from the end using Array.length
We know that Array.length is used to get the count of items that exist in an array. But we can also use this to remove items from the end of an array. We just need to set the length of array and it will remove all the other items from the array.
Code Example
let arr = [10, 20, 30, 40, 50];
arr.length = 3;
console.log(arr);
Output
[10,20,30]
- Add new item at first position of array using unshift() method Javascript
- Test every item of array against some condition in javascript
- Lodash - Get index of array item based on some condition
- Lodash - Find item index from array by searching from the end
- Remove duplicate values from an array in Javascript
- How to Remove duplicate elements from array in JavaScript ?
- Javascript code to remove falsy value like null, undefined, false from array