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

2 Comments

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.