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 straightforward. 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.
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.
This method requires a few more lines, but it is slightly different in a few ways from the previous example:
indexOf
the array item to be removed, and then we splice
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.
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.
Also Published here