- #javaScript
- #arrays
- #snippets
Create an array
Create an array of items in a shopping list. Below is an array for my favourite meal, Spaghetti alla Carbonara.
const shopping_list = ['eggs', 'bacon', 'garlic', 'olive oil', 'spaghetti', 'basil'];
Find and delete item in array
If the bacon has been bought it needs to be removed from the list. Create a function that takes the item as an argument.
function removeItemFromShoppingList(item) {
}
The array needs to be looped through to:
- find the item.
- remove the item using the splice() method.
function removeItemFromShoppingList(item) {
for (let i = 0; i < shopping_list.length; i++) {
if (shopping_list[i] === item) { // find
shopping_list.splice(i, 1) // delete
}
}
}
Call the function
Pass into the function the item to be deleted, in this case ‘bacon’.
removeItemFromShoppingList('bacon')
This results in the updated array.
['eggs', 'garlic', 'olive oil', 'spaghetti', 'basil'];
That’s it.
Thank you for stumbling across this website and for reading my blog post entitled Find element in array and delete it