In this article, we will be removing elements from an array in JavaScript. We can use a different method for removing elements.
These are the methods:
This method is used to remove the last element of the array and returns the removed element. This function decreases the length of the array by 1.
Example:
Javascript
function func() {
let arr = [ "shift" , "splice" , "filter" , "pop" ];
let popped = arr.pop();
console.log( "Removed element: " + popped);
console.log( "Remaining elements: " + arr);
}
func();
|
OutputRemoved element: pop
Remaining elements: shift,splice,filter
This method is used to remove the first element of the array and reduce the size of the original array by 1.
Example:
Javascript
function func() {
let arr = [ "shift" , "splice" , "filter" , "pop" ];
let shifted = arr.shift();
console.log( "Removed element: " + shifted);
console.log( "Remaining elements: " + arr);
}
func();
|
OutputRemoved element: shift
Remaining elements: splice,filter,pop
The JavaScript Array splice() method can be used to remove any particular element from an array in JavaScript. Moreover, this function can be used to add/remove more than one element from an array.
Syntax:
array.splice(index, howmany, item1, ....., itemX)
Return Value: A new Array, containing the removed items (if any).
Example: This example uses the splice() method to remove a particular element from an array.
Javascript
let Arr = [ "C++ " , " Java " ,
" Python " , " Go " , " Prolog" ];
function removeElement() {
Arr.splice(2, 1);
console.log(Arr);
}
removeElement();
|
Output[ 'C++ ', ' Java ', ' Go ', ' Prolog' ]
This method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function.
Example:
Javascript
function isPositive(value) {
return value > 0;
}
function func() {
let filtered = [101, 98, 12, -1, 848].filter(isPositive);
console.log( "Positive elements in array: " + filtered);
}
func();
|
OutputPositive elements in array: 101,98,12,848
Use the delete operator to remove elements from a JavaScript array.
Example:
Javascript
let array = [ "lowdash" , "remove" , "delete" , "reset" ]
let deleted = delete array[2];
console.log( "Removed: " + deleted);
console.log( "Remaining elements: " + array);
|
OutputRemoved: true
Remaining elements: lowdash,remove,,reset
The _.remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.
Example:
Javascript
let array = [101, 98, 12, -1, 848];
let evens = _.remove(array, function (n) {
return n % 2 == 0;
});
console.log( "odd elements: " + array);
console.log( "even elements: " + evens);
|
Output:
odd elements: 101, -1
even elements: 98, 12, 848
Supported Browsers: The browser supported by the Array splice() Method is listed below:
- Google Chrome
- Apple Safari
- Firefox
- Opera
- Edge