> ## Content Index
> Fetch the complete content index at: https://www.ggorantala.dev/llms.txt
> Use this file to discover other available public pages before exploring further.

# How can I remove a specific item from an array in JavaScript?
- URL: https://www.ggorantala.dev/how-can-i-remove-a-specific-item-from-an-array-in-javascript/
- Published: 2023-05-19T07:11:51.000Z
- Updated: 2023-11-08T03:52:38.000Z
- Description: Removing a specific item from an array is the most use case a developer runs into. You will learn more than 7 ways to achieve this.
- Author: Gopi Gorantala
- Tags: JavaScript, React.js

## Introduction

The most common use case a Javascript or frontend developer runs into is "removing an item from an array."

In JavaScript, removing an item from an array can be done in several ways.

## 🤑 Partner Discounts

1. [20% off on Educative.io + 20% Holiday Season Promo](https://www.educative.io/gopi)
2. [ZeroToMastery 30% Flat Discount Code: PPP\_30 ](https://academy.zerotomastery.io/a/aff%5Fgtscpyrf/external?affcode=441520%5Fuzodzrlr)
3. [Get 50% Off From Skillshare](http://em.impact.com/ls/click?upn=lcFF8ubtmveum2UxN6LiFoKWRUe-2BW78J2-2FqkRtupDAE7TVdIyd6k0sEfgwG8wckprCqPa3yMv8-2FK4j5CrXPhLQ-3D-3DFCZw%5FeqGtEkAAAfhKV5weTbv3TD-2BfR-2BOaXd-2FbFeEtH-2FPxoVtRf3FjDUUl1DYNVJKUaAgYlh5CAIhJah-2BwisC2jlbmjH3d4bRPLM-2FLwL84x6zrwrXYcgU3N-2BMbMUIJ-2BsPfN-2FVOO7KCVNE-2F-2BhFhrU7lL4luu0tOSFJc3fYYkoAYVYpkcYhLf8Gts1zAatDY9mQr06p7NISc6529EErnwB2yUQzaaelkIk9Ed2y5AATsgZkOArAB3WPNVfo-2BXelLrJvitjfgkiokC42XyC5o3L5CibdAVmUdytVN2a6Orp-2FSGkJ2Ukc-3D)
4. [Coursera Flat 70% off on selected courses](https://imp.i384100.net/Py07NM)
5. [Up to 20% discount on DataCamp (Limited Offer)](https://datacamp.pxf.io/R5mKgb)
6. [Memrise: 28% discount on lifetime access (Join 65 million learners)](https://memrise.pxf.io/vNxWGj)
7. [Udacity: Up to 70% OFF on Udacity's nanodegree](https://imp.i115008.net/AoyJMN)
8. [Flat 50% off on Linux Foundation boot camps, 30% on bundles, and certifications](https://shareasale.com/r.cfm?b=734319&u=2943848&m=59485&urllink=&afftrack=).

## How to replicate this?

Let us assume we have some items in the array as follows:

```js
const array = [10, 20, 30, 40, 50];

console.log(array); // [10, 20, 30, 40, 50]
```

You can run this snippet directly on google chrome developer tools under the sources tab, create a snippet, and you are good to run JavaScript snippets directly on the browser.

![](https://storage.ghost.io/c/e3/0b/e30b8112-16a4-4a70-8441-b0c5d5f2b4d7/content/images/2023/05/Screenshot-2023-05-19-at-08.16.32.png)

For example, to remove an element at the index `2`, which is the item `30`. We must write some logic to remove/delete the element from the array. Following are various ways we can remove an element from an array.

## How can we achieve this?

There are different ways to remove a specific item from an array in JavaScript. Let us take a look at each of them.

1. using `splice()`.
2. using `filter()`.
3. Using a traditional loop.
4. Using `slice()` with spread operator
5. Using `indexOf()` and `slice()` methods
6. Using `reduce()`
7. Using `splice()` and `lastIndexOf()`

## Different ways to remove an item from the array

### Using splice() ( ✅ Recommended )

The `splice()` method is a built-in function in JavaScript that allows you to modify an array by adding, removing, or replacing elements. It can be used to change the contents of an array by removing or replacing existing elements or by adding new elements in their place. 

The `splice()` method operates directly on the array and returns the modified array.

#### Approach #1

The following `array` variable holds an array of `5` elements. Let us remove an element at the index `2`. 

```js
const array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

// remove an element at index `2`
const indexToRemove = 2; // index of item to remove
array.splice(indexToRemove, 1);
console.log(array); // Output: [ 10, 20, 40, 50 ]
```

The `splice()` method takes two arguments: the index of the item to remove and the number of items to remove. In this example, we remove one item from the index `2`.

#### Approach #2

What if we want to delete an item and don't know where the element is located in the array? How can we find the index of it?

JavaScript API has provided `indexOf` a method to find the element's index in the array. Let us see the code in action.

```js
const array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

const itemToRemove = 30; // item we want to remove
const index = array.indexOf(itemToRemove); // get index of the item

if (index !== -1) { // only splice array when item is found
    array.splice(index, 1);
}

console.log(array); // Output: [ 10, 20, 40, 50 ]

```

### Using filter()

The `filter()` method creates a new array containing all the elements that pass a specific condition. You can use it to create a new array that excludes the item you want to remove. Here's an example:

```java
let array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

const itemToRemove = 30; // item we want to remove

array = array.filter(function (item) {
    return item !== itemToRemove;
});

console.log(array); // [ 10, 20, 40, 50 ]
```

### Using a for-loop

You can iterate over the array and copy all elements except the one you want to remove into a new array. 

Here's an example:

```js
let array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

const itemToRemove = 30; // item we want to remove

const newArray = [];
for (let i = 0; i < array.length; i++) {
    if (array[i] !== itemToRemove) {
        newArray.push(array[i]);
    }
}

console.log(newArray); // Output: [ 10, 20, 40, 50 ]
```

### Using the slice() with the Spread operator

The `slice()` method returns a shallow copy of a portion of an array into a new array. In this example, we create a new array by concatenating the original array's first portion up to the item's index to remove, with the second portion of the original array after the item's index to remove.

```java
let array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

const indexToRemove = 2; // index to remove
const newArray = [...array.slice(0, indexToRemove), ...array.slice(indexToRemove + 1)];
console.log(newArray); // Output: [ 10, 20, 40, 50 ]

```

### Using indexOf() and slice()

You can combine the `indexOf()` method to find the index of the item and the `slice()` method to create a new array excluding that item. 

Here's an example:

```js
let array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

var itemToRemove = 30; // item to remove

var index = array.indexOf(itemToRemove);
if (index !== -1) { // only slice array when item is found
    array = array.slice(0, index).concat(array.slice(index + 1));
}

console.log(array); // Output: [ 10, 20, 40, 50 ]

```

### Using reduce()

The `reduce()` method can iterate over the array and accumulate the desired elements into a new array. 

Here's an example:

```js
let array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

const itemToRemove = 30; // item to remove

array = array.reduce(function (acc, curr) {
    if (curr !== itemToRemove) {
        acc.push(curr);
    }
    return acc;
}, []);

console.log(array); // Output: [ 10, 20, 40, 50 ]
```

### Using splice() and lastIndexOf()

If you want to remove all occurrences of a specific item, you can combine `splice()` with `lastIndexOf()` to remove the items from the end of the array first. 

Here's an example:

```js
let array = [10, 20, 30, 40, 50];
console.log(array); // [ 10, 20, 30, 40, 50 ]

const itemToRemove = 30; // item to remove

let index = array.lastIndexOf(itemToRemove);
while (index !== -1) {
    array.splice(index, 1);
    index = array.lastIndexOf(itemToRemove);
}

console.log(array); // Output: [ 10, 20, 40, 50 ]

```

These are a few additional ways to remove a specific item from an array in JavaScript. Each approach may have its own advantages depending on your specific use case.

## Conclusion

There are multiple ways to remove a specific item from an array in JavaScript. Whether you choose to use `splice()`, `filter()`, or iterate through the array, depending on your use case: selectively eliminate the item and update the array accordingly. 

Your approach may depend on factors such as efficiency, code readability, or personal preference. 

With these techniques in your toolkit, you can confidently manipulate arrays in JavaScript and remove specific elements as needed.

> Recommended Courses:

The following courses help you learn true basics and advanced Javascript concepts.

1. [JavaScript in Detail: From Beginner to Advanced](https://www.educative.io/courses/javascript-in-detail-from-beginner-to-advanced?aff=xjzd&ref=ggorantala.dev).
2. [Learn Object-Oriented Programming in JavaScript](https://www.educative.io/courses/learn-object-oriented-programming-in-javascript?aff=xjzd&ref=ggorantala.dev).
3. [Decode the Coding Interview in JavaScript: Real-World Examples](https://www.educative.io/courses/decode-coding-interview-js?aff=xjzd&ref=ggorantala.dev).
4. [Meta Frontend Developer Professional Certificate](https://imp.i384100.net/Pyjz1R?ref=ggorantala.dev) (Coursera course by Meta)
5. [JavaScript: The Advanced Concepts](https://academy.zerotomastery.io/a/aff%5Fszrvh5nm/external?affcode=&affcode=441520%5Fuzodzrlr&ref=ggorantala.dev).
6. [JavaScript Web Projects: 20 Projects to Build Your Portfolio](https://academy.zerotomastery.io/a/aff%5F693qyg0h/external?affcode=&affcode=441520%5Fuzodzrlr&ref=ggorantala.dev).

## 📚 Top Recommended Books

1. [JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language 7th Edition](https://amzn.to/3Y0PTxL)
2. [Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming 3rd Edition](https://amzn.to/43mjwu6)
3. [Learn JavaScript Quickly: A Complete Beginner’s Guide to Learning JavaScript, Even If You’re New to Programming (Crash Course With Hands-On Project)](https://amzn.to/3NOL8m8)
4. [The Road to React: Your journey to master plain yet pragmatic React.js](https://amzn.to/3D8Tv7e)

## Next up?

Read the following articles:

[How to Prevent cannot read property split of undefinedIntroduction The “cannot read property split of undefined” error occurs when we try to call the split() method on a variable that stores an undefined value. In JavaScript, a variable is said to be undefined if it has been declared but not initialized. In simple words, when we do not![](https://storage.ghost.io/c/e3/0b/e30b8112-16a4-4a70-8441-b0c5d5f2b4d7/content/images/size/w256h256/2023/05/icon-4.png)👨🏻‍💻 Gopi GorantalaGopi Gorantala![](https://storage.ghost.io/c/e3/0b/e30b8112-16a4-4a70-8441-b0c5d5f2b4d7/content/images/2023/02/prevent-cannot-read-property-undefined.png)](https://www.ggorantala.dev/how-to-prevent-cannot-read-property-split-of-undefined/)

[A Complete Guide To JavaScript localStoragelocalStorage is a property of the window object in JavaScript that allows you to store key/value pairs in a web browser. The data stored in localStorage persist even after the browser is closed, making it a useful tool for saving user data on the client side.![](https://storage.ghost.io/c/e3/0b/e30b8112-16a4-4a70-8441-b0c5d5f2b4d7/content/images/size/w256h256/2023/05/icon-4.png)👨🏻‍💻 Gopi GorantalaGopi Gorantala![](https://storage.ghost.io/c/e3/0b/e30b8112-16a4-4a70-8441-b0c5d5f2b4d7/content/images/2023/02/JavaScript-Local-Storage-3.png)](https://www.ggorantala.dev/javascript-localstorage/)

## 🤑 Partner Discounts

1. [20% off on Educative.io + 20% Holiday Season Promo](https://www.educative.io/gopi)
2. [ZeroToMastery 30% Flat Discount Code: PPP\_30 ](https://academy.zerotomastery.io/a/aff%5Fgtscpyrf/external?affcode=441520%5Fuzodzrlr)
3. [Get 50% Off From Skillshare](http://em.impact.com/ls/click?upn=lcFF8ubtmveum2UxN6LiFoKWRUe-2BW78J2-2FqkRtupDAE7TVdIyd6k0sEfgwG8wckprCqPa3yMv8-2FK4j5CrXPhLQ-3D-3DFCZw%5FeqGtEkAAAfhKV5weTbv3TD-2BfR-2BOaXd-2FbFeEtH-2FPxoVtRf3FjDUUl1DYNVJKUaAgYlh5CAIhJah-2BwisC2jlbmjH3d4bRPLM-2FLwL84x6zrwrXYcgU3N-2BMbMUIJ-2BsPfN-2FVOO7KCVNE-2F-2BhFhrU7lL4luu0tOSFJc3fYYkoAYVYpkcYhLf8Gts1zAatDY9mQr06p7NISc6529EErnwB2yUQzaaelkIk9Ed2y5AATsgZkOArAB3WPNVfo-2BXelLrJvitjfgkiokC42XyC5o3L5CibdAVmUdytVN2a6Orp-2FSGkJ2Ukc-3D)
4. [Coursera Flat 70% off on selected courses](https://imp.i384100.net/Py07NM)
5. [Up to 20% discount on DataCamp (Limited Offer)](https://datacamp.pxf.io/R5mKgb)
6. [Memrise: 28% discount on lifetime access (Join 65 million learners)](https://memrise.pxf.io/vNxWGj)
7. [Udacity: Up to 70% OFF on Udacity's nanodegree](https://imp.i115008.net/AoyJMN)
8. [Flat 50% off on Linux Foundation boot camps, 30% on bundles, and certifications](https://shareasale.com/r.cfm?b=734319&u=2943848&m=59485&urllink=&afftrack=).