Deleting array elements in JavaScript – delete vs splice

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?

For example:

  • Confusion with javascript array.splice()
  • Javascript “shift” versus “splice” - are these statements equal?
  • Javascript: What's a better way to splice arrays together than what I'm using now?
  • Array splicing with coffeescript, what is _ref for?
  • Funny behaviour of Array.splice()
  • Comparing and Filtering two arrays
  • myArray = ['a', 'b', 'c', 'd'];
    
    delete myArray[1];
    //  or
    myArray.splice (1, 1);
    

    Why even have the splice method if I can delete array elements like I can with objects?

  • Funny behaviour of Array.splice()
  • how to remove specific row from list in angularjs
  • How to remove all element from array except the first one in javascript
  • How to loop through a shrinking array
  • Understanding result returned from splice in CoffeeScript
  • Confusion with javascript array.splice()
  • 20 Solutions collect form web for “Deleting array elements in JavaScript – delete vs splice”

    delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

    > myArray = ['a', 'b', 'c', 'd']
      ["a", "b", "c", "d"]
    > delete myArray[0]
      true
    > myArray
      [undefined, "b", "c", "d"]
    

    Splice(start, deleteCount) actually removes the element from the array:

    > myArray = ['a', 'b', 'c', 'd']
      ["a", "b", "c", "d"]
    > myArray.splice(0, 2)
      ["a", "b"]
    > myArray
      ["c", "d"]
    

    Array.remove() Method

    John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.

    // 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);
    };
    

    and here’s some examples of how it could be used:

    // Remove the second item from the array
    array.remove(1);
    // Remove the second-to-last item from the array
    array.remove(-2);
    // Remove the second and third items from the array
    array.remove(1,2);
    // Remove the last and second-to-last items from the array
    array.remove(-2,-1);
    

    John’s website

    Because delete only removes the object from the element in the array, the length of the array won’t change. Splice removes the object and shortens the array.

    The following code will display “a”, “b”, “undefined”, “d”

    myArray = ['a', 'b', 'c', 'd']; delete myArray[2];
    
    for (var count = 0; count < myArray.length; count++) {
        alert(myArray[count]);
    }
    

    Whereas this will display “a”, “b”, “d”

    myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);
    
    for (var count = 0; count < myArray.length; count++) {
        alert(myArray[count]);
    }
    

    I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here’s a comparison of splice and delete for removing every 'c' from the items Array.

    var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
    
    while (items.indexOf('c') !== -1) {
      items.splice(items.indexOf('c'), 1);
    }
    
    console.log(items); // ["a", "b", "d", "a", "b", "d"]
    
    items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
    
    while (items.indexOf('c') !== -1) {
      delete items[items.indexOf('c')];
    }
    
    console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
    ​
    

    From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :

    When you delete an array element, the
    array length is not affected. For
    example, if you delete a[3], a[4] is
    still a[4] and a[3] is undefined. This
    holds even if you delete the last
    element of the array (delete
    a[a.length-1]).

    It’s probably also worth mentioning that splice only works on arrays. (Object properties can’t be relied on to follow a consistent order.)

    To remove the key-value pair from an object, delete is actually what you want:

    delete myObj.propName;     // , or:
    delete myObj["propName"];  // Equivalent.
    

    splice will work with numeric indices.

    whereas delete can be used against other kind of indices..

    example:

    delete myArray['text1'];
    

    delete acts like a non real world situation, it just removes the item, but the array length stays the same:

    example from node terminal:

    > var arr = ["a","b","c","d"];
    > delete arr[2]
    true
    > arr
    [ 'a', 'b', , 'd', 'e' ]
    

    Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1

    function(arr,arrIndex){
        return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
    }
    

    What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.

    Here is an example using the function above as a node module, seeing the terminal will be useful:

    > var arr = ["a","b","c","d"]
    > arr
    [ 'a', 'b', 'c', 'd' ]
    > arr.length
    4 
    > var arrayRemoveIndex = require("./lib/array_remove_index");
    > var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
    > newArray
    [ 'a', 'b', 'd' ] // c ya later
    > newArray.length
    3
    

    please note that this will not work one array with dupes in it, because indexOf(“c”) will just get the first occurance, and only splice out and remove the first “c” it finds.

    If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.

    You can do it by building a new array. e.g

    function reindexArray( array )
    {
           var result = [];
            for( var key in array )
                    result.push( array[key] );
            return result;
    };
    

    But I don’t think you can modify the key values in the original array, which would be more efficient – it looks like you might have to create a new array.

    Note that you don’t need to check for the “undefined” entries as they don’t actually exist and the for loop doesn’t return them. It’s an artifact of the array printing that displays them as undefined. They don’t appear to exist in memory.

    It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?


    Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:

    reindexArray : function( array )
    {
        var index = 0;                          // The index where the element should be
        for( var key in array )                 // Iterate the array
        {
            if( parseInt( key ) !== index )     // If the element is out of sequence
            {
                array[index] = array[key];      // Move it to the correct, earlier position in the array
                ++index;                        // Update the index
            }
        }
    
        array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
    },
    

    delete Vs splice

    when you delete an item from an array

    var arr = [1,2,3,4]; delete arr[2]; console.log(arr)
    //result
    [1, 2, 3: 4]
    

    when you splice

    var arr = [1,2,3,4]; arr.splice(1,1); console.log(arr)
    //result
     [1, 3, 4]
    

    in case of delete the element is deleted but the index remains empty

    while in case of splice element is deleted and the index of rest elements is reduced accordingly

    As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:

    The splice() method changes the content of an array by removing existing elements and/or adding new elements.

    var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
    
    myFish.splice(2, 0, 'drum'); 
    // myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
    
    myFish.splice(2, 1); 
    // myFish is ["angel", "clown", "mandarin", "sturgeon"]
    

    Syntax

    array.splice(start, deleteCount[, item1[, item2[, ...]]])

    Parameters

    start

    Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

    deleteCount

    An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

    If deleteCount is omitted, deleteCount will be equal to (arr.length - start).

    item1, item2, …

    The elements to add to the array, beginning at the start index. If you don’t specify any elements, splice() will only remove elements from the array.

    Return value

    An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

    […]

    you can use something like this

    var my_array = [1,2,3,4,5,6];
    delete my_array[4];
    console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));
    

    Should display [1, 2, 3, 4, 6]

    function remove_array_value(array, value) {
        var index = array.indexOf(value);
        if (index >= 0) {
            array.splice(index, 1);
            reindex_array(array);
        }
    }
    function reindex_array(array) {
       var result = [];
        for (var key in array) {
            result.push(array[key]);
        }
        return result;
    }
    

    example:

    var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
    remove_array_value(example_arr, 'banana');
    

    banana is deleted and array length = 2

    They’re different things that have different purposes.

    splice is array-specific and, when used for deleting, removes entries from the array and moves all the previous entries up to fill the gap. (It can also be used to insert entries, or both at the same time.) splice will change the length of the array (assuming it’s not a no-op call: theArray.splice(x, 0)).

    delete is not array-specific; it’s designed for use on objects: It removes a property (key/value pair) from the object you use it on. It only applies to arrays because standard (e.g., non-typed) arrays in JavaScript aren’t really arrays at all*, they’re objects with special handling for certain properties, such as those whose names are “array indexes” (which are defined as string names “…whose numeric value i is in the range +0 ≤ i < 2^32-1“) and length. When you use delete to remove an array entry, all it does is remove the entry; it doesn’t move other entries following it up to fill the gap, and so the array becomes “sparse” (has some entries missing entirely). It has no effect on length.

    A couple of the current answers to this question incorrectly state that using delete “sets the entry to undefined“. That’s not correct. It removes the entry (property) entirely, leaving a gap.

    Let’s use some code to illustrate the differences:

    console.log("Using `splice`:");
    var a = ["a", "b", "c", "d", "e"];
    console.log(a.length);            // 5
    a.splice(0, 1);
    console.log(a.length);            // 4
    console.log(a[0]);                // "b"

    Currently there are two ways to do this

    1. using splice()

      arrayObject.splice(index, 1);

    2. using delete

      delete arrayObject[index];

    But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.

    IndexOf accepts also a reference type. Suppose the following scenario:

    var arr = [{item: 1}, {item: 2}, {item: 3}];
    
    var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]
    
    var l = found.length;
    while(l--) {
      var index = arr.indexOf(found[l])
      arr.splice(index, 1);
    }
    
    console.log(arr.length); //1
    

    Differently:

    var item2 = findUnique(2); //will return {item: 2}
    var l = arr.length;
    var found = false;
      while(!found && l--) {
      found = arr[l] === item2;
    }
    
    console.log(l, arr[l]);// l is index, arr[l] is the item you look for
    

    If the desired element to delete is in the middle (say we want to delete ‘c’, which its index is 1):

    var arr = ['a','b','c'];

    You can use:

    var indexToDelete = 1;
    var newArray = arr.slice(0, indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

    Easiest way is probably

    var myArray = ['a', 'b', 'c', 'd'];
    delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
    myArray = _.compact(myArray); ['a', 'c', 'd'];
    

    Hope this helps.
    Reference: https://lodash.com/docs#compact

    Why not just filter? I think it is the most clear way to consider the arrays in js.

    myArray = myArray.filter(function(item){
        return item.anProperty != whoShouldBeDeleted
    });
    
    function deleteFromArray(array, indexToDelete){
      var remain = new Array();
      for(var i in array){
        if(array[i] == indexToDelete){
          continue;
        }
        remain.push(array[i]);
      }
      return remain;
    }
    
    myArray = ['a', 'b', 'c', 'd'];
    deleteFromArray(myArray , 0);
    

    // result : myArray = [‘b’, ‘c’, ‘d’];