MODERN METHODS TO REMOVE ITEMS FROM ARRAYS IN JAVASCRIPT
Tags: javascript, tutorial, beginners, webdev
Published: 2020-04-20 22:41:41

---
title: MODERN METHODS TO REMOVE ITEMS FROM ARRAYS IN JAVASCRIPT
published: true
description: This explains the different ways to remove items in JavaScript beyond the built-in array methods
tags: JavaScript, tutorial, beginners, webdev
cover_image: https://res.cloudinary.com/drquzbncy/image/upload/v1587318828/javascript_arrays_ab7slm.jpg
---

## Table of Contents
  1. [Arrays In JavaScript](#chp-1)
  2. [Array.prototype.shift()](#chp-2)
  3. [Array.prototype.pop()](#chp-3)
  4. [The Delete Operator](#chp-4)
  5. [Array.prototype.splice()](#chp-5)
  6. [Array.prototype.filter()](#chp-5)
  7. [A Masterpiece](#chp-7)
  8. [Closing Thoughts](#chp-8)

#### 1. Arrays In JavaScript <a name="chp-1"></a>
Arrays in JavaScript are special objects that store items sequentially, that is, they store items one after another in memory. They are high-level, list-like objects.  You can actually think of them as lists of items. 

All items in an array have an index which indicates the position of that item in the array. The item in the first position has an index of 0 then next has an index of 1 etc. For this reason, JavaScript's array indexes are zero-based.
Items in JavaScript arrays can be accessed using their index.
We can find the index of an item in an array using a special method called the *indexOf*.

***You can simply think of JavaScript arrays as an ordered set of values that you refer to with a name and an index*** 

{% runkit %}
const listOfAnimals = [ "dog", "cat", "rat", "fish", "rabbit" ]

console.log(listOfAnimals) // returns the listOfAnimals array
console.log(listOfAnimals[0]) // gets the item at index 0 
console.log(listOfAnimals[2]) // gets the third item which is the item at index 2

let itemPosition = listOfAnimals.indexOf("rat") // gets the index of the item passed. here "rat"

console.log(itemPosition) // displays the index of "rat" in the listOfAnimals array
{% endrunkit %}

The total number of items in an array is the length of that array.
The length property is special. It always returns the index of the last element plus one.
{% runkit %}
const evenNumbers = [2,4,6,8,10,12]
console.log(evenNumbers.length) // returns the length of the evenNumbers array
{% endrunkit %}

JavaScript arrays are the most used data structure and because they organize items sequentially, it is super easy to access the first and last item. Hence deleting these items are very easy in JavaScript.

#### 2. Array.prototype.shift() <a name="chp-2"></a>

The *shift()* method removes the first element in an array (that is the item at the index of zero). It also re-orders the remaining elements in the array and decrements the array length by one. Finally, it returns the removed item.

{% runkit %}  
const languages = [ "PHP", "Python", "Rust", "C++", "C", "Ruby", "JavaScript" ]
const removedLanguage = languages.shift()
console.log(removedLanguage) // returns "PHP"
console.log(languages) // returns new array without "PHP"
{% endrunkit %}

#### 3. Array.prototype.pop() <a name="chp-3"></a>

The *pop()* method is the opposite of the *shift()*. It removes the last element of the array.
The index of the last element in the array is the length of the array minus one. The *pop()* method, also decrements the array length by one and returns the removed element.

{% runkit %}  
const frameworks = [ "React.js", "Angular", "Vue.js", "Express.js", "Ember.js" ]
const removedFramework = frameworks.pop()
console.log(removedFramework) // returns "Ember.js"
console.log(frameworks) // returns new array without "Ember.js"
{% endrunkit %}

#### 4. The Delete Operator <a name="chp-4"></a>
Both the *pop()* and the *shift()* methods give us a way to remove elements from an array from pre-set position viz: the last or first positions respectively. While they are great, we do not get the freedom of deleting elements from any other position. What if we want to delete elements at a certain index which is neither the first nor the last?

The **delete operator** is great for this.
Unlike **pop()** and **shift()** the **delete operator** returns the new array. 
{% runkit %}
const items = ["eggs", "meat", "vegetables", "salad", "rice", "fish" ]
delete items[3]

console.log(items)
console.log(items.length)
console.log(items[3])
{% endrunkit %}

*One thing that must be noted before one should use the delete method is that it does not change the length of the array as seen above. It removes the specified element and adds* ***undefined*** *in its place.* 

#### 5. Array.prototype.splice() <a name="chp-5"></a>
If the **delete operator** is not very suitable for you because it does not update the array length, another built-in array method you can use is the **splice()** method.

The **splice()** method is a very powerful built-in array method that can be used to remove array elements at any index. It can also be used to add elements or replace an existing element. *But we will just stick to removing elements from an array.* It can remove multiple elements from an array unlike **pop()** and **shift()** that removes one element at a time.
Lastly the **splice()** method returns a new array containing the deleted element/elements. 

*The* ***splice()*** *method can take up to three parameters for our use case it needs only two. The first specifies the index to start deleting from the second specifies how many elements to remove from the array*

{% runkit %}
//remove single element
const numbersInWords = [ "one", "two", "three", "four", "five", "dozen", "six" ]
const arrayWithDeletedItems = numbersInWords.splice(5, 1) //returns ["dozen"]

// remove multiple elements
const mammals = ["man", "dog", "rat", "cat", "fish", "snake", "fly"]
const nonMammals = mammals.splice(4, 3) // return ["fish", "snake", "fly"]

console.log(numbersInWords)
console.log(arrayWithDeletedItems)
console.log(mammals)
console.log(nonMammals)
{% endrunkit %}

#### 6. Array.prototype.filter() <a name="chp-6"></a>
We saw the power of  **splice()** above as we used it to elements from any index in an array. But with **splice()** we could only delete multiple elements in series. 

{% runkit %}
const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20]
const result = numList.splice(7, 5)

console.log(result)
console.log(numList)
{% endrunkit %}

What if we want to delete all the words from our numList array above? since the words are not in series in the above array **splice()** is not the best fit. Except we are implementing our own **remove()** method where we can use it under the hood. *A good option is to use the* **filter()** *since we are deleting all instance of a string in the array.*

The **filter()** methods calls a provided callback function once for each element in an array and returns a new array of elements that passes the test implemented in the callback function.

{% runkit %}
const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20]
pureNumList = numList.filter(item => typeof item !== "string") // returns a list of numbers
pureEvenNumber = numList.filter(item => typeof item !=="string" && item % 2 === 0) // returns a list of only even numbers. 


console.log(numList)
console.log(pureNumList)
console.log(pureEvenNumber)
{% endrunkit %}

Noticed the power of the **filter()** method, how it allows us to remove multiple elements from an array regardless of their index. Also, notice how we can combine conditions in the callback function implementation to target multiple elements.

{% runkit %}
const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20]

pureEvenNumber = numList.filter(item => typeof item !=="string" && item % 2 === 0) // returns a list of only even numbers. 

console.log(pureEvenNumber)
{% endrunkit %}

#### A Masterpiece <a name="chp-7"></a>
There are still other ways to do this in JavaScript, truly at this point, it should boil down to a developer's implementation of his own custom function. Maybe you dream of a **remove()** method of your own. I will leave you with a masterpiece from **John Resig**. (The creator of *jQuery*).

{% runkit %}
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

const numList = [1,2,3,4,5,6,"Half-dozen",7,8,9,10,11,12,"one-dozen",13,14,15,16,17,18,19,20]

numList.remove(13)
numList.remove(6)
console.log(numList) // returns a new array with only numbers.
{% endrunkit %}

#### 8. Closing Thoughts <a name="chp-8"></a>
These are a nice collection of ways to remove items from an array but it is by no means an exhaustive list. As I said developers can always come up with something novel. If you do have a custom helper function to achieve this task, you are more than welcome to share it in the comment section below.