let myArray = [ 'some', 'array', 'content' ];
splice method that all arrays have. Let's look at how it works.
If you just want to delete an item from an array, you only have to use
splice with two arguments. The first is the index you want to start from, and the second is how many items you want to delete. For example, if we want to delete 2 items, starting at index 0 from our array, we'd do the following:
let myArray = [ 'some', 'array', 'content' ]; myArray.splice(0, 2); // Will return [ 'content' ] console.log(myArray);
As you might've noticed,
splice actually alters the original array. So be careful when doing this, as a copy of the original will not be made! Here are some other examples to consider:
myArray.splice(3, 1); // Removes one item, at index 3 myArray.splice(0, 5); // Removes 5 items, at index 0 (i.e. from the start of the array);
In a similar vein, we can also delete an item from an array by value, but this is a little bit more tricky. We have to use both
splice for this to work:
- First, we get the index of the item we want to delete by value, using
- Then, we use that number to delete the array item.
Here's an example. We want to delete the item ravioli from our array below. First, we get the index of that item, using
arr1.indexOf('ravioli'). This will return
2, since that is the index of ravioli in our array. Then, we use that number to splice out one element at that index using
splice(itemIndex, 1). Now, ravioli is removed from our array!
let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ]; let itemIndex = arr1.indexOf('ravioli'); // Returns [ 'potato', 'banana', 'carrot' ], since ravioli has an index of 2 arr1.splice(itemIndex, 1); console.log(arr1);
pop() method is an easy way to delete only the last element in an array. Just like
splice, it mutates your original array, so a copy of your original array will not be kept:
let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ]; // Returns 'carrot' console.log(arr1.pop()); // Returns [ 'potato', 'banana', 'ravioli' ] console.log(arr1);