remove elements from array using javascript

How to Remove Specific Item From Array in JavaScript

JavaScript arrays are powerful data structures that allows you to store large amount of diverse data in a compact manner. Often while working with JS arrays, you may need to delete specific elements from the array. In this article, we will learn how to remove specific item from array in JavaScript.


How to Remove Specific Item From Array in JavaScript

Let us say you have the following array in JavaScript.

arr = [1, 2, 3];

Let us say you want to remove element ‘2’ from the above array. For this purpose, we will use splice() method, which adds and/or removes array elements. Its syntax is as shown below.

array.splice(index, howmany, item1, ....., itemX)

In the above command,

index - (Required) Position to add/remove items. 0 is the first element. Negative value defines the position from the end of the array.
howmany	- (Optional) no. of elements to be removed

item1, ..., itemX - (Optional)New elements(s) to be added.

So we use indexOf() function to get the position of element that we want to delete from array.

index = arr.indexOf(2);
if (index > -1) {
  arr.splice(index, 1); // 2nd parameter means remove one item only
}

Finally, we print the updated array.

console.log(arr); 

You will see the following output.

[1, 3]

In this article, we have learnt how to delete specific items from array in JavaScript.

Also read:

Detect Mobile Device in JavaScript
How to Detect Click Outside Element in JavaScript
How to Capitalize First Letter in JavaScript
Python Run Shell Command & Get Output
How to Generate All Permutations in Python List

Leave a Reply

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