How to remove a specific item from an array in JavaScript ?


In this article, we learn about how to remove a specific item from an array in JavaScript.

To remove a specific element of an array we have to first find the position of the element in the array and then remove it.

To get the position of the specific element we have to know the index of that element in the array. to get the index we will use indexOf() method in JavaScript.

Once we know the index of that element , then we can use splice() to remove it from the array.

array.indexOf

The indexOf() method in JavaScript return the index in which the element is found in an array.

Syntax:

indexOf(searchElement)

array.splice()

The splice() method add or remove an element in am array by its index. It takes two argument : start , which is the index in the array, and deleteCount, the number of element it will remove from an array from start.

Syntax:

splice(start, deleteCount)

Remove specific element from an array in JavaScript

Now using the indexOf() and splice() we will be able to remove element from middle of an array in JavaScript.

For example, we will remove an item 'orange' from an array of fruits.

Step 1: Get the index of the item 'orange' from the fruits array using indexOf()

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const index = fruits.indexOf('Orange')
console.log(index)

// 1

Step 2 : Now we will use the index of the element (here orange) to remove it from the array using splice()

const fruits = ["Banana", "Orange", "Apple", "Mango"];

const index = fruits.indexOf('Orange')

const newArr = fruits.splice(index, 1)

console.log(fruits)

OUTPUT :

[ 'Banana', 'Apple', 'Mango' ]

By using this method you can remove object from array by it's property.

Related Topics:

How To Insert An Item Into An Array At A Specific Index In JavaScript?

How To Remove Object From Array In JavaScript?

How To Convert An Array To Object In Javascript?

How To Copy Or Clone An Array In JavaScript

How To Convert An Array To String In Javascript

How To Empty An Array in JavaScript?


💾 Recommended Articles