Skip to content

Instantly share code, notes, and snippets.

@Harrisonkamau
Last active November 29, 2020 12:40
Show Gist options
  • Save Harrisonkamau/6a2adbb0f53c34251f4685546659accf to your computer and use it in GitHub Desktop.
Save Harrisonkamau/6a2adbb0f53c34251f4685546659accf to your computer and use it in GitHub Desktop.
Remove a specific item from an Array in JavaScript. All instances of that item will be removed
// Adding to the prototype so it can be used like a normal array method
Array.prototype.removeItem = function removeItem(item) {
const formattedItem = typeof item === 'string' ? item.trim().toLowerCase() : item;
const formattedItems = this.map((currentItem) => {
if (typeof currentItem === 'string') {
return currentItem.toLowerCase();
};
return currentItem;
});
if (formattedItems.indexOf(formattedItem) === -1) {
throw new Error('Item not found');
}
const newArray = this.filter((currentItem) => {
if (typeof currentItem === 'string') {
return currentItem.toLowerCase() !== formattedItem
}
return currentItem !== formattedItem;
});
return newArray;
};
// USAGE
// strings
const names = ['Jane', 'John', 'Matthew', 'Mark'];
names.removeItem('jane');
// integers
const numbers = [12,14,15];
console.log(numbers.removeItem(14));
// floats
const floats = [0.9, 0.2, 0.25];
console.log(floats.removeItem(0.9));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment