9 Ways to Remove Elements From A JavaScript Array

remove-puzzle-piecesJavaScript arrays allow you to group values and iterate over them. You can add and remove elements in different ways. Unfortunately there is not a simple Array.remove method. Instead there are a variety of ways you can clean array values.

You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. You can also use the JavaScript Array filter method to create a new array with desired items.

JavaScript Array elements can be removed from the end of an array by setting the length property to a value less than the current value. Any element whose index is greater than or equal to the new length will be removed.


var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); //  [1, 2, 3, 4]

You can remove specific array elements using the delete operator:


var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6

Using the delete operator does not affect the length property. Nor does it affect the indexes of subsequent elements. The array becomes sparse, which is a fancy way of saying the deleted item is not removed but becomes undefined. Compare using delete with the splice method described below.

Removing Elements from End of a JavaScript Array

The pop method removes the last element of the array, returns that element, and updates the length property. The pop method modifies the array on which it is invoked, This means unlike using delete the last element is removed completely and the array length reduced.


var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]

Removing Elements from Beginning of a JavaScript Array

The shift method works much like the pop method except it removes the first element of the array instead of the last:


var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]

The shift method returns the element that has been removed, updates the indexes of remaining elements, and updates the length property. It modifies the array on which it is invoked.

Using Splice to Remove Array Elements

The splice method can be used to add or remove elements from an array. The first argument specifies the location at which to begin adding or removing elements. The second argument specifies the number of elements to remove. The third and subsequent arguments are optional; they specify elements to be added to the array.

Here we use the splice method to remove two elements starting from position three (zero based index):


var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var removed = array.splice(2,2);

/*
removed === [3, 4]
array === [1, 2, 5, 6, 7, 8, 9, 0]
*/

An array containing the removed elements is returned by the splice method. You can see the removed array contains [3, 4] and the original array contains the remaining values.

The splice method can also be used to remove a range of elements from an array.


["bar", "baz", "foo", "qux"]

list.splice(0, 2) 
// Starting at index position 0, remove two elements ["bar", "baz"] and retains ["foo", "qux"].

Removing Array Items By Value Using Splice

If you know the value you want to remove from an array you can use the splice method. First you must identify the index of the target item. You then use the index as the start element and remove just one element.


var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

for( var i = 0; i < array.length-1; i++){ 
   if ( array[i] === 5) {
     arr.splice(i, 1); 
   }
}

//=> [1, 2, 3, 4, 6, 7, 8, 9, 0]
This is a simple example where the elements are integers. If you have an array of objects you would need a more sophisticated routine.

Using the Array filter Method to Remove Items By Value

Unlike the splice method, filter creates a new array. filter() does not mutate the array on which it is called, but returns a new array.

filter() has a single parameter, a callback method. The callback is triggered as the filter method iterates through the array elements. It will pass three values to the callback: the current value or element, the current array index and the full array.

The callback method should return either true or false. It is your responsibility to test the value (element) to see if it meets your criteria. If it does you can return true. Elements that return true are added to the new, filtered array.


var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

var filtered = array.filter(function(value, index, arr){

    return value > 5;

});

//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

You should note a new array containing matching values is returned. The original array is left untouched. I find this useful because I often want to retain an original data source, but retrieve subsets based on different logic sets.

The Lodash Array Remove Method

Sometimes utility libraries are the best way to solve more complex problems. Lodash provides a rich set of array manipulation methods, one being remove.

The Lodash remove method works much like the array filter method, but sort of in reverse. It does not save the original array values, but removes matching elements. It returns the matching elements as a new array.


var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
  return n % 2 === 0;
});

console.log(array);
// => [1, 3]

console.log(evens);
// => [2, 4]

Making a Remove Method

As I mentionmed before, there is no native Array.remove method. The Lodash method does solve this problem, but you may not always want to use Lodash. This does not mean you cannot create a utility method. John Resig gave us a model to follow, however he extended the Array prototype, which is a bad idea.

Instead I created an Array remove utility method that can be added to a helper or utility library. Like the Lodash remove method the first parameter is the target array. It uses Array.filter to return elements not matching a value.


function arrayRemove(arr, value) {

   return arr.filter(function(ele){
       return ele != value;
   });

}

var result = arrayRemove(array, 6);

// result = [1, 2, 3, 4, 5, 7, 8, 9, 0]
This method is simple, it assumes simple values like numbers or strings. You could modify this method to use a custom comparison method, but I think it would be easier to just use the filter method directly.

Summary

Removing JavaScript Array items is important to managing your data. There is not a single 'remove' method available, but there are different methods and techniques you can use to purge unwanted array items.

This article has reviewed these methods and how they can be used. You also saw how to create a helper method that makes removing items from an array a bit easier and consistent.

Share This Article With Your Friends!

Googles Ads Facebook Pixel Bing Pixel LinkedIn Pixel