In this short tip post, we will learn how to remove a particular element from an array in JavaScript.
Table of Contents
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.
This only remove 1 particular element from index ,not all in array. you need to loop in array.
Yes, we intend to remove one particular element only. If you wanna remove everything from an array, just assign it to null. No need for a loop.
Nice example Shahid, this is a very elegant way to remove a single element from an array. A few thing to be careful with when emptying arrays:
Array.length deletes everything in the array, including other references. In other words, if you have two references to the same array and you delete the array’s contents using Array.length, both references will now point to the same empty array.
Emptying an array by initializing a new array assigns a reference to the new array variable, while excluding other references. This means that references to the contents of the previous array are still kept in memory, which can commonly leading to memory leaks.
^ Make sure you avoid the memory leaks guys 🙂
Cheers