JavaScript array has a variety of ways you can remove element from array.
1) Using splice() function
Find the index of the array element you want to remove using indexOf, and then remove that index with splice.
var arrayList = [1, 2, 3];
var index = arrayList.indexOf(2);
if (index > -1) {
arrayList.splice(index, 1);
}
console.log(arrayList);
// Output = [2, 9]
2) Using pop() method
The pop method removes the last element of the array, returns that element, and updates the length property.
var arrayList = [1, 2, 3];
arrayList.pop();
console.log( arrayList );
// Output = [1, 2]
3) Using shift() method
The shift method removes the first element of the array, returns that element, and updates the length property.
var arrayList = ['1', '2', '3'];
arrayList.shift();
console.log( arrayList );
// Output = ['2', '3']
4) Using filter() method
The filter() has a single parameter, a callback method.
var arrayList = [1, 2, 3, 4, 5];
var filtered = arrayList.filter(function(value, index) {
return value > 3;
});
console.log( filtered );
// Output => [4, 5]
5) Using the Delete Operator
You can remove specific array elements using the delete operator:
var arrayList = [1, 2, 3, 4, 5, 6];
delete arrayList[4]; // delete element with index 4
console.log( arrayList );
// [1, 2, 3, 4, undefined, 6]
There are different methods and techniques you can use to purge unwanted array items. You can suggest more methods in the below comment box.
0 Comments