Delete That Element!
Tags: javascript, beginners, codenewbie
Published: 2020-04-25 04:42:32

Manipulating data sets is something developers do often and there are many different ways to go about it. When I was first learning JavaScript coming from a language like Ruby, it was interesting to see what built-in Array methods were available and where one would have to get creative to implement their own solution. Deleting an element from an array is like the latter, as there is is no out of the box `delete()` or `remove()` method, so I wanted to explore in this post a few ways to go about it.

As with anything else, there are questions you should ask yourself before implementation. These include: 

  * Do I need to remove an element by its value or based on its index?
  * Do I need to remove one element or multiple elements based on the above answer?
  * Should I mutate the dataset when deleting my element(s)?

###Existing Methods at Your Disposal
Existing built-in Array methods used to delete an element from an array that should be in your tool box are `filter()` and `splice()`. Both methods will return different values and serve different purposes but will get the job done in removing an element. There are also `shift()` and `pop()` but these are specific to only the first and last element in the array. 

###Deleting Element Based On Its Value
Let's say you know the value of something you want removed from the array. The following examples will be food related because why not. I want to remove 'ice cream' because I've gotten tired of eating it lately (a blasphemous thing to say and write). 

```javascript
const favFoods = ['noodles', 'dumplings', 'ice cream', 'cake'];
```
####Non-Destructively
Deleting an element in an array by value using `filter()` will not mutate your original input but will return you a new array with only the elements passing the condition "filtered" in. 

The below example illustrates that only values that do not equal 'ice cream' will be collected into a new array.
```javascript
// filter() syntax
array.filter(callback(currentVal[, optional-index, [optional-array]])

const newFavFoods = favFoods.filter(food => food !== 'ice cream'); 
// ['noodles', 'dumplings', 'cake'];
```
If I had multiple 'ice cream' elements in my array, they all would be filtered out in the new returned array.
```javascript
const favFoods = ['noodles', 'ice cream', 'dumplings', 'ice cream', 'cake'];
const newFavFoods = favFoods.filter(food => food !== 'ice cream'); 
// ['noodles', 'dumplings', 'cake'];
```

What if you wanted to only remove one 'ice cream'? You could find the index of the first instance of 'ice cream' with `indexOf()`, and then use the found index to not include that element when using filter.

```javascript
const favFoods = ['noodles', 'ice cream', 'dumplings', 'ice cream', 'cake'];
const idx = favFoods.indexOf('ice cream'); // 1
const newFavFoods = favFoods.filter((food, i) => i !== idx); 
// ['noodles', 'dumplings', 'ice cream', 'cake'];
```

####Destructively 
Though I try not to mutate original data and generally prefer the above method when deleting an element from an array, there are times when you may see a coding challenge that requires you to modify an array in-place.

When removing one element from your array destructively, you can use `indexOf()` in conjunction with `splice()`, as the first argument in `splice()` specifies the index to add/remove items. The second argument is how many items you want removed, which is 0 by default.

```javascript
// splice() syntax
array.splice(index, howManyToRemove, addItem1, ...) 

let favFoods = ['ice cream', 'noodles', 'dumplings', 'ice cream', 'cake'];
const idx = favFoods.indexOf('ice cream'); // 0
const newFavFoods = favFoods.splice(idx, 1); ['ice cream']
newFavFoods; // ['noodles', 'dumplings', 'ice cream', 'cake'];
```
If you wanted to remove all values of 'ice cream' in the array, you can loop over it and remove any values that equal 'ice cream' using `splice()`. **Remember to decrement your loop counter each time it's successful or else you may skip over unchecked elements in the array as it grows or shrinks.**
```javascript
let favFoods = ['ice cream', 'noodles', 'dumplings', 'ice cream', 'cake'];
for (let i = 0; i < favFoods.length; i++) {
  if (favFoods[i] === 'ice cream') {
    favFoods.splice(i, 1);
    i--;
  }
}
console.log(favFoods); // ['noodles', 'dumplings', 'cake'];
```

###Deleting Element Based On Its Index
The above methods can also be used to delete a specific element in your array by its index. However, if you want to **delete the first element of your array or delete the last element of your array, there are `shift()` and `pop()`,** respectively, to help with that. 

Keep in mind that both **`shift()` and `pop()` will mutate your data** and will return the element that was removed.

```javascript
let favFoods = ['ice cream', 'noodles', 'dumplings', 'cake'];
favFoods.pop(); // 'cake'
favFoods; // ['ice cream', 'noodles', 'dumplings'];
favFoods.shift(); // 'ice cream'
favFoods; // [ 'noodles', 'dumplings']
```

###Using the `delete` Operator
JavaScript does have a `delete` operator that removes a property from an object. As arrays are objects, you can use this operator on an array, however, it has its limitations and may not be as useful to you. 

While using the `delete` operator will remove the element from the array, the length of the array will not change and index at the removed element will be an empty item.
```javascript
let favFoods = ['ice cream', 'noodles', 'dumplings', 'cake'];
delete favFoods[2]; // true
favFoods; // ['ice cream', 'noodles', <1 empty item>, 'cake'];
```
If you want an array element to not be empty and to have an undefined value, you can instead reassign the value as undefined.
```javascript
let favFoods = ['ice cream', 'noodles', 'dumplings', 'cake']; 
favFoods[2] = undefined; // undefined
favFoods; // [undefined, 'noodles', 'dumplings', 'cake'];
```

One last consideration I'll mention would be to forgo an array and use a JavaScript `Set` object instead, as a `Set` only allows for unique values and has a built-in `delete()` method that would mutate the `Set`. You can read my blog post about Sets [here](https://dev.to/katkelly/ditching-dupes-with-a-set-4cf3)!

These are just a few of the ways to delete an element from an array. There are other ways to tackle this that may involve JavaScript libraries but I wanted to keep the examples simple with existing JavaScript methods. Happy coding!

Resources
[Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
)
[Array.prototype.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)