how to remove a particular element from an array

How to Remove a Particular Element from an Array in JavaScript

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);

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.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

3 Comments

  1. 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

Leave a Reply to Shahid (UnixRoot) Shaikh Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.