Remove an Item From an Array with JavaScript

By  on  

One operation that seems to be more difficult than it should be in every programming language is removing a value from an array.  It's such an easy concept mentally that it skews our programmatic view of the task.  In JavaScript the splice method is of huge help in removing an item from an array.

JavaScript Splice

One splice coupled with an indexOf removes the item from an array:

// Start with an initial array
var array = ["a", "b", "c"];

// Find and remove item from an array
var i = array.indexOf("b");
if(i != -1) {
	array.splice(i, 1);
}

Of course if you'd like to remove multiple occurrences of the same string/number, you'll need add a bit more logic:

for(var i = array.length-1; i--;){
	if (array[i] === "b") array.splice(i, 1);
}

You may be thinking that the filter method would work...

array.filter(function(i) {
	return i != "b"
});

...but that will return a new array, thus not modifying the original.

Removing a given value from an array isn't too difficult of a task when you have a reliable snippet nearby!

Recent Features

Incredible Demos

  • By
    Duplicate DeSandro’s CSS Effect

    I recently stumbled upon David DeSandro's website when I saw a tweet stating that someone had stolen/hotlinked his website design and code, and he decided to do the only logical thing to retaliate:  use some simple JavaScript goodness to inject unicorns into their page.

  • By
    jQuery Chosen Plugin

    Without a doubt, my least favorite form element is the SELECT element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true is, well, a disaster.  Needless to say, whenever a developer goes...

Discussion

  1. It’s important to note that splicing an array is an incredibly slow operation and is very difficult or impossible for engines to optimize. If you have performance sensitive uses of collections of items that need to be mutated at arbitrary points then you’ll likely want to look into alternative data structure implementations. Two new ones being introduced as base language features in ES6 are Map and Set, which force uniqueness but also allow for linear time item deletions. While these features only exist in Spidermonkey and V8 behind a flag, there are shims available and they will eventually be in all engines.

    • Awesome tip Brandon, thank you!

    • Oops, quick correction. That’s *constant* time, not *linear* time.

  2. Steve Fink

    nit: you start out looking past the end of the array. I think you want array.length - 1.

    I haven’t benchmarked, but if you’re expecting to remove a lot of elements, it might be faster to do something like:

    for (var i = 0, j = 0; i < array.length; i++) {
      if (array[i] != "b")
        array[j++] = array[i];
    }
    array.length = j;
    
    • MaxArt

      I don’t know how much is “a lot” of elements, but your code (although nice) doesn’t seem to be very fast… At least, not faster than .splice:
      http://jsperf.com/removing-items-from-array
      In this case I’m just trying to remove 10% of the elements, maybe with a higher ratio the scenario would be different.

    • David

      @MaxArt: Your code has a little mistake: Instead of checking for b!==5, your should check for b[i]!==5. Otherwise, you just get “Array” for b, which is always false. Without this little mistake, Steve’s code is way faster.

    • I’m quite surprised by those results, Steve’s version should be faster than shifting all elements back one index each splice. I guess splice must have a clever implementation in the other browsers and Firefox 21 just has a beast JS interpreter :P

  3. indexOf doesn’t work on array in IE :(

    • MaxArt

      It does in IE9+.
      For IE8- there are common shims, but I guess you already know that.

  4. Al Jey

    Even though filter does in fact return a new array, it is a much more efficient way to get rid of multiple items at once than a several calls to splice, and as such should be preferred.

  5. Hey everyone, I’m new to contributing but stoked on javascript and the open source community so here I go.

    If you’re not concerned about keeping the array organized I came up with this which is blazing fast in comparison:

    if (i > 0) callbacks[i] = callbacks[0];
    callbacks.shift();
    

    Otherwise you will need to run a loop to shift all elements after the one you want to remove -1 index which depending on the size of the array could get ridiculous but in the majority of case would still crush splice.

    Let me know what you think or send me an email. I’m just getting started on Git to get more involved.

    • I was curious about your technique so I built a jsPerf test around it. Unfortunately, it appears array.splice still performs better than the method you described.

      http://jsperf.com/array-splice-vs-reassign-and-shift

      It was certainly a good idea and comes close to splice (except in FF), but since it destroys the ordering of the array, adds an extra line of code, and still doesn’t match splice, I’d recommend sticking with splice.

      I haven’t looked into the browser implementation code for splice. Maybe that’s something you would want to do to find if you can help optimize it further; otherwise, it might help you understand how arrays work behind-the-scenes.

  6. Hello David,
    I am new to java script and starting to learn about arrays. I understand pop and push. I would like to know how to use the splice code snippet you have posted. How would I use the splice code in my java script file?

    // tasks.js #2
    // This script manages a to-do list.
    
    // Need a global variable:
    var tasks = []; 
    
    // Function called when the form is submitted.
    // Function adds a task to the global array.
    function addTask() {
        'use strict';
    
        // Get the task:
        var task = document.getElementById('task');
    
        // Reference to where the output goes:
        var output = document.getElementById('output');
        
        // For the output:
        var message = '';
    
        if (task.value) {
        
            // Add the item to the array:
            tasks.push(task.value);
            
            // Update the page:
            message = 'To-Do';
            for (var i = 0, count = tasks.length; i < count; i++) {
                message += '' + tasks[i] + '';
            }
            message += '';
            output.innerHTML = message;
            
        } // End of task.value IF.
    
        // Return false to prevent submission:
        return false;
        
    } // End of addTask() function.
    
    // Initial setup:
    function init() {
        'use strict';
        document.getElementById('theForm').onsubmit = addTask;
    } // End of init() function.
    window.onload = init;
    
  7. Hey guys, I’m okay with js but still learning. I’ve been looking everywhere on how to time a function to END after a certain period of time, say two days. Any help? Would really appreciate any advice! Thanks in advance.

  8. Chirag64

    Your for loop for removing multiple occurrences of the same string/number is wrong. It doesn’t have any condition like i > -1;. Although it still seems to work, it doesn’t really check the last element of the array. So if you had an array like

    var array = ["a", "c", "b"];
    

    , it wouldn’t remove the ‘b’ element.

  9. Hey you have explained it very well but will it work if there is same value in array. i mean if duplicate data then what it will do. ?

    in my case i want to delete on the bases of key so what can i do ?
    please can you suggest me some solution.

  10. Timmah

    When you do this:

    for(var i = array.length-1; i--;){
    	if (array[i] === "b") array.splice(i, 1);
    }
    
    and array = ["a", "b", "b", "c", "d"];
    

    since splice re-indexes the array, won’t you miss the second “b”?

  11. carla

    in duplicated data

    If you remove the -1 it will work

    for(var i = arr.length; i--;){
    	if (arr[i] === "b") arr.splice(i, 1);
    }
    

    or reset the index

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

    Yes, removing multiple occurrences doesn’t work for array like ['a', 'a', 'a'].
    I think this should work:

    for(var i = 0; i< array.length; i++){
       while(array[i] == item) array.splice(i,1);
    }
    
  13. Aneudys Amparo

    Here my example, It took me like 18hrs trying to do.
    I have to array, One is the original but before to give the data to the User i have to extract/delete the data that had been completed by the same User.

    var offers =  server.offers;
    var completions = server.completions;
    
                         offers.forEach(function(offer, indexO) {
    
                                    completions.forEach(function(completion, indexC){
    
                                        if(offer.id == parseInt(completion.offerId)) {
                                            //Delete that offer
    
                                            offers.splice(indexO, 1);
    
                                        }
                                    });
                                  });
    
    
  14. To remove multiple occurrences, I believe this would be much faster than looping through the whole array:

    var index = array.indexOf("b");
    while (index > -1) {
        array.splice(index,1);
        index = array.indexOf("b");
    }
    

    This can easily be put into a function as such:

    function removeValueFromArray(value, array) {
        var index = array.indexOf(value);
        while (index > -1) {
            array.splice(index,1);
            index = array.indexOf(value);
        }
        return array;
    }
    
  15. james

    There’s a bug in your code: array.length-1 should be array.length

    for(var i = array.length; i--;){
    	if (array[i] === "b") array.splice(i, 1);
    }
    
    • Dagge

      james, that was what I said and somehow my coment got removed and yours came up the same day

    • Dagge

      … I see Carla mention it too

  16. Dagge

    Not array.length-1 … it has to be just array.length to remove in the last position too

  17. Toni

    Imagine something like:

    const newItem = ['item 1', 'item 0', 'item 1', 'item 2', 'item 1', 'item 0'];
    

    If I want to remove all ‘item 1’ I can use:

    for(let i = newItem.length-1; i--;){
    	if (newItem[i] === "item 1") newItem.splice(i, 1);
    }
    

    The question is if I have an array inside another array how can I do?

    const newItem = [
    	['item 1', 'item 0', 'item 1'],
    	['item 2', 'item 1', 'item 0']
    ];
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!