How to remove a specific item from an array
π£ Sponsor
One of the most frequent tasks we have to perform in Javascript is to remove a particular item from an array. However, itβs not straight forward. There is no removeArrayItem
method in Javascript, so we have to use alternative methods. Letβs look at how to remove a particular array item in Javascript.
How to remove a specific array item in Javascript
Option 1: Using filter()
The easiest way with modern Javascript to remove a specific array item is using filter. Letβs look at a simple example:
let myArr = [ "π", "π", "π", "π" ];
// Creates a new array without "π" - so [ "π", "π", "π" ]
let removedArr = myArr.filter((x) => x !== "π");
console.log(removedArr);
This works great when we have an array where every element is unique. Unfortunately, it starts to break down if you only want to remove one item, and there are duplicates. Letβs look at another example:
let myArr = [ "π", "π", "π", "π" ];
// Creates a new array without "π" - so [ "π", "π" ]
let removedArr = myArr.filter((x) => x !== "π");
console.log(removedArr);
Since we had two green apples, and the new array filters out all green apples, we actually remove two items when using this method. If we only want to remove one element, we have to use an alternative strategy.
Option 2: Use indexOf() and splice()
This method requires a few more lines, but it is slightly different in a few ways from the previous example:
- First of all, it alters the original array - so we arenβt making a copy here. The original array will be mutated
- Secondly, it uses two functions - first we get the
indexOf
the array item to be removed, and then wesplice
the array to remove that single item.
Here is an example:
let myArr = [ "π", "π", "π", "π" ];
let getLocation = myArr.indexOf("π");
myArr.splice(getLocation, 1);
// myArr now becomes [ "π", "π", "π" ];
console.log(myArr);
This example may be preferable in some situations, but ultimately youβll need to decide what works best in your own code.
Conclusion
Although there is no straightforward way to remove an item from an array in Javascript, we do have two tools that give us enough flexibility to cover pretty much any use case regarding array item removal. If you want to learn more quick array tips, check out my array tips guide here.
More Tips and Tricks for Javascript
- How to Make Payments with the Javascript Payments API
- How to get the Full URL in Express on Node.js
- Javascript ShadowRealms
- Converting Binary to Decimal
- How the Javascript History API Works
- Art Generator with Javascript and WebGL
- Javascript Comments
- Removing the last element of an array in Javascript
- Javascript Array Every Method
- An Introduction to Javascript Objects