How to remove a particular element from Array in JavaScript

Removing a particular element from an array in JavaScript is a very common programming paradigm that developers often run into. Removing the last element from an array can be very easy and can be done simply using the pop() function. But what if you want to remove a particular element from an array in JavaScript.

Removing particular element using splice() in JavaScript

The splice() method is used when the index of the element to be removed is known. But the point to be remembered is that the arrays in JavaScript starts from the index 0.¬† The splice() method takes two numbers as it’s argument, first being the index of the element to be removed and the second being the number of elements to be removed following the index.

const Array = ["Mom", "Dad", "Son", "Daughter"] 
//splice(Starting Index to be removed, No. of elements to be removed following starting index) 
Array.splice(1,2)

Output

["Mom","Daughter"]

The splice() is great method to edit an array as it does not create a new array and directly make the changes in the Original Array.

But what if you don’t want to edit the original array and create a new array? We use slice() method to get this done.

Removing particular element using slice() in JavaScript

slice() returns a portion of an array into a new array object. It is to be noted that the last element will not be copied into the new array.




var fruits = ['banana', 'apple', 'orange', 'mango', 'lemon'];

var fresh = fruits.slice(1, 4);

Output

['apple', 'orange', 'mango']

Learn more about

Learn more awesome JavaScript programs: click here


Leave a Reply

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