Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

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?

share|improve this question
2  
This is a dupe of stackoverflow.com/questions/495764/… – andynormancx Feb 1 '09 at 11:24
For .splice in loops, have a look at this question: Delete from array in javascript. – Rob W Feb 20 '12 at 14:29
@Mohsen You have 9,000 reputation. Please get one more – helloworld Apr 6 at 18:17
@andynormancx Yes, but this answer was posted just the day after, and got so many more votes - I'd say it's better written, that must be it. – Camilo Martin May 26 at 12:43

14 Answers

up vote 669 down vote accepted

Delete won't remove the element from the array it will only set the element as undefined.

So,

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray
  [undefined, "b", "c", "d"]
> myArray.splice(0, 2)
  [undefined, "b"]
> myArray
  ["c", "d"]
share|improve this answer
33  
correction for line 3: [undefined, 'b', 'c', 'd'] (it's not the string 'undefined', but the special value undefined) – Jasper Dec 5 '09 at 15:55
1  
Clear explanation +1 – Etienne Dupuis Dec 10 '10 at 21:36
   
excellent answer! – Greg Oct 8 '11 at 10:09
11  
Actually, delete does remove the element, but does not reindex the array or update its length (which is already implied by the former since the length is always the highest index+1). – Felix Kling Jun 20 '12 at 18:11
2  
JSlint doesn't like delete myArray[0] syntax saying "Expected an operator and instead saw 'delete'." Using splice is recommended. – Eye Oct 11 '12 at 10:27
show 2 more comments

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

share|improve this answer
2  
+1 For Array.remove(). However it's not happy being passed string arguments (unlike most Array methods, eg [1,2,3].slice('1'); // =[2,3]), so it's safer to change it to var rest = this.slice(parseInt(to || from) + 1 || this.length); – Richard Inglis Jun 15 '12 at 15:10
I found that this was causing an asynchronous problem. Does the thread get given up before the this.push.apply() ? – tomwrong Aug 23 '12 at 9:34
1  
@tomwrong, there are no threads in javascript, and the function executes this.push.apply(this, rest), then returns the value it returned – billy Apr 4 at 12:00
2  
@ryandif This answer has nothing to do with jQuery except that the poster refers to the same author (John R). It is perhaps not relevant anyway as an answer, but it is probably helpful for many people coming here from search engines. – David May 4 at 17:04
2  
Why not just use splice()? The name of this function, the parameter names and the results aren't obvious. My recommendation is to just use splice(index,length) - (see Andy Hume's answer) – auco May 31 at 9:22
show 5 more comments

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]);
}
share|improve this answer
8  
great example except the ambiguity in the second example by using 1,1 - the first 1 refers to the index in the array to start the splice, the second 1 is the number of elements to remove. So to remove 'c' from the original array, use myArray.splice(2,1) – thedawnrider Jul 6 '12 at 6:33
Good point, I've included your suggested improvement to remove the ambiguity. – andynormancx Aug 24 '12 at 9:25

also check out Resig's array remove: http://ejohn.org/blog/javascript-array-remove/

share|improve this answer
This link is broken. :( – BMiner May 31 '11 at 20:18
1  
@ BMiner .. works for me right now :) – zack Jun 1 '11 at 8:44
@Pacerier I think you mis-read that, see Resig's response to Eich's comment: "As far as slice vs. splice – slice just seemed like the easier method to be interacting with, and after running some quick speed tests, it seemed to be, more consistently faster." – zack Mar 8 '12 at 20:15
@zack You are right that I mis-read that. Still, my point is you should not use that script if you care about performance because copying the elements in-place and reducing the length will be more performant than the splice + reduce-length + push implementation shown on that page. – Pacerier Mar 8 '12 at 20:58

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"]
​
share|improve this answer

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]).

share|improve this answer

splice will work with numeric indices.

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

example:

delete myArray['text1'];
share|improve this answer
7  
When you say 'any other kind of indices', you're not talking about arrays any more, but rather objects, which is what the OP is asking about. – Yi Jiang Jan 23 '11 at 16:58
@YiJiang: Arrays are Objects. Indizes are properties. There is no difference. – Bergi May 24 '12 at 22:55
myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(function(v) { return v != 'a';});
share|improve this answer
Awesome, never thought to use filter for a delete. Nice answer. – Wes Grant Jan 2 at 19:27
1  
How about just return v != 'a'? – minitech Apr 28 at 17:05

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)
},
share|improve this answer

Underscore's compact function does the trick:

From the docs:

compact_.compact(array) Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

_.compact([0, 1, false, 2, '', 3]); => [1, 2, 3]

share|improve this answer
1  
Underscore has without method: > Returns a copy of the array with all instances of the values removed. – Vladimir Starkov Dec 4 '12 at 8:24

For deleting you also can use this way:

var arr = [1, 2, 3, 4, 5];
arr.length = 2; // shorten to 2 elements

//result:
alert(arr); // [1, 2]
share|improve this answer
Completly out of content – todotresde Feb 27 at 17:49

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.
share|improve this answer

You can iterate over each array-item and splice it if it exist in your array.

function destroy(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) arr.splice(i, 1);
    }
    return arr;
}
share|improve this answer

this also works beautifully. plus it leaves the original array as well so that if you only want a new array with the key deleted it will be nice

    window.Array.prototype.remove = function (key) {
    var _array = [];
    delete this[key];
    for (var item in this) {
        if (this[item])
            _array.push(this[item]);
    }
    return _array;
};
share|improve this answer

protected by Community Jun 20 '12 at 18:06

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.