In this short tip post, we will learn how to remove a particular element from an array in JavaScript.
Objective
For a given array and an element, our code should find and delete that element (if exists) from an array and returns us new array.
Approach
We need to first find the position of an element and then delete it. We can use indexOf() method to find the position and splice() method to delete the element.
Code
Here is the code.
var num = [10,20,30,4,5,6,112,333,4,2,5,66];
function deleteElement(arr, element) {
var position = arr.indexOf(element);
if(position === -1) {
return null;
}
return arr.splice(position,1);
}
console.log('Old array = ', num)
deleteElement(num,5);
console.log('New array = ', num);
function deleteElement(arr, element) {
var position = arr.indexOf(element);
if(position === -1) {
return null;
}
return arr.splice(position,1);
}
console.log('Old array = ', num)
deleteElement(num,5);
console.log('New array = ', num);
Check out the codepen for the live demo.
See the Pen
delete element array by Shahid Shaikh (@codeforgeek)
on CodePen.
Love JavaScript? Learn more about it here.