How to remove a specific item from an array
Option 1: Using filter()
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
indexOfthe array item to be removed, and then we
splicethe 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.
- Setting the Default Node.JS version with nvm
- Scheduling and Runnning Recurring Cron Jobs in Node.JS
- How to install nvm, the Node Version Manager