Remove Elements From An Array With Javascript

There are 2 main methods of removing an element from an array in javascript, splice and delete.
I’ll discuss both methods, provide examples and detail out the benefits and drawbacks of each.

.splice()

         var myArray = ["dog", "cat", "fish", "duck"];

        var itemToRemove = "fish";
        var indexOfItemToRemove;

        //use indexOf to determine the position in the array that the item appears
        indexOfItemToRemove = myArray.indexOf(itemToRemove);


        //Use the splice method of your array object, passing in the index of the item you want to remove and how many occurances of that item you want to remove
        //splice removed the elements from the array in-place and outputs an array of items that it removed
        //splice will completely remove the element from the array, leaving no empty array positions
        var removedItems;
        if (indexOfItemToRemove > -1) {
            removedItems = myArray.splice(indexOfItemToRemove, 1);
        }

        alert("indexOfItemToRemove = " + indexOfItemToRemove +
            " removedItems Count = " + removedItems.length +
            " myArray Length = " + myArray.length);
    

Using splice, you will remove the element from the array, and it will return an array of items that were removed.
The array is modified in-place, meaning that when the elements are removed from the array the elements after the one that was just removed shift forwards, which updates their indexes and the length property of the array.
This means that if you plan to use the iterative method in order to remove the elements from the array you will need to iterate through it backwards.

        var removedItems;
        for (var i = myArray.length; i--;) {
            if (myArray[i] == itemToRemove) {
                removedItems = myArray.splice(i, 1);
            }
        }

        alert("count in myArray =" + myArray.length
            + " count of removed items from array=" + removedItems.length);
    

If you try to iterate forwards, not only will you certainly be accessing the incorrect item in the array, but you may even get an index out of range error.
Suppose the item that was removed from the array was the second to last item in the array, when you get to the last item, the index position will be 1 out, because the last item’s index has reduced by 1.

If you decide to use the indexOf method to remove the elements from the array, you won’t have to worry about this, but keep in mind that the indexOf method doesn’t work for older browsers (IE 9+ and FireFox 1.5+).

If compatibility with older browsers isn’t a concern, I recommend you use the indexOf method as you don’t have to iterate over the array at all to remove a specific item.

However, if you need to remove many items from the array (like all instances of “fish” for example) you would have to iterate over the array, and in each iteration check if indexOf returns -1 ,indicating that the item you’re looking for isn’t in the array.
Alternatively you can use JQuery’s $.inArray() method (Discussed later).

         var i = myArray.indexOf(itemToRemove);
        while (i > -1) {
            myArray.splice(i, 1);
            i = myArray.indexOf(itemToRemove);
        }

        alert("count in myArray =" + myArray.length
            + " index of item to remove " + myArray.indexOf(itemToRemove));
    

delete myArray[index]

         //this will completely remove this item but not update the indexes of the array items or the length property of the array.
        //the existing array is modified in-place, and is safe to iterate forwards
        for (var i = 0; i < myArray.length; i++) {
            if (myArray[i] == itemToRemove) {
                delete myArray[i];
            }
        }

        alert("value of removed item is " + myArray[2])

        alert("count in myArray =" + myArray.length
            + " index of item to remove " + myArray.indexOf(itemToRemove));
    

Using delete is the alternative method to remove an element from an array.

When you use the delete method it will remove the item from the array without changing the indexes of the other items in the array, but it also won’t update the length property as instead of removing the item from the array completely, it will instead leave an empty item.

Think of it like having a string variable and then setting it’s value to an empty string.  The variable still exists but it has no content.

If you try to access one of the deleted array items, it will return undefined.

JQuery - Getting An Item’s Index In An Array - $.inArray()

If you want to use indexOf() but need to be compatible with older browsers, you can use the $.inArray() method of JQuery.
Under the hood, If it determines that indexOf() is not possible, JQuery will be iterating over the array checking for matches, but it means that you don’t have to clutter your code with the loops, nor concern yourself with whether or not the user has an older browser which doesn’t support indexOf().

             var jqindexOfItemToRemove = $.inArray(itemToRemove, myArray);
            alert(jqindexOfItemToRemove);
    

The first parameter is the item you’re looking for, the second parameter is the array to search through.  The third parameter is the index to start iterating from, it default to zero so I’ve left it out of my example.
The result is the same as indexOf() in that the zero based index position is returned if the item is in the array and if it’s not in the array it will return -1.

If you enjoyed this article, please consider giving it a +1

Tags: javascript, array, jquery

Published: 5/17/2014 8:21:02 AM
By: Stephen Warren