I have an array of integers, which I'm using the .push() method to add to.

Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int);.

I have to use core JavaScript - no frameworks are allowed.

share|improve this question
29  
If you need to support <IE9 (sigh) then check this SO question regarding indexOf in IE. – Scotty.NET Sep 13 '13 at 7:48
    
(lodash) array = ['a', 'b', 'c']; _.pull(array, 'a') // array => ['b', 'c']; See also stackoverflow.com/questions/5767325/… – Chun Yang Aug 25 '15 at 20:28
    
filter method can do what you want. – Salvador Dali Sep 5 '15 at 23:43
    
You can use delete but it will not rearange the index instead it will set this slot to 'undefined × 1'. For example: var list = [1,2,3,4,5,6] -> delete list[1] -> [1, undefined × 1, 3, 4, 5, 6]. – Fox May 24 at 23:26
    
delete should be more performant in the short term, because it won't have to shift the later items. forEach, map and filter will automatically skip processing for undefined (deleted) items. But it's probably not ideal if you will be adding a lot of things to your array in future, or reading it many times. – joeytwiddle Jul 29 at 8:55

42 Answers 42

up vote 5057 down vote accepted

First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(5);

Note: browser support for indexOf is limited; it is not supported in Internet Explorer 7 and 8.

Then remove it with splice:

if (index > -1) {
    array.splice(index, 1);
}

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


If you need indexOf in an unsupported browser, try the following polyfill. Find more info about this polyfill here.

Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {
    var a;
    if (null == this) throw new TypeError('"this" is null or not defined');
    var c = Object(this),
        b = c.length >>> 0;
    if (0 === b) return -1;
    a = +e || 0;
    Infinity === Math.abs(a) && (a = 0);
    if (a >= b) return -1;
    for (a = Math.max(0 <= a ? a : b - Math.abs(a), 0); a < b;) {
        if (a in c && c[a] === d) return a;
        a++
    }
    return -1
});
share|improve this answer
100  
Good solution, but some browsers don't suppoer array.indexOf – Peter Olson Apr 23 '11 at 22:25
130  
The second argument to the splice function is how many elements to remove. – Tom Wadley Apr 23 '11 at 22:25
46  
array.indexOf is not supported in IE8 or earlier (see w3schools.com/jsref/jsref_indexof_array.asp). jQuery.inArray() works similarly though (api.jquery.com/jQuery.inArray) – Jon Onstott May 17 '13 at 17:15
38  
Dangerous! If you are working with dynamic values (add and remove dynamic values from array) and value is not exist in array (the index become -1) the code above will remove the last element of the array. – Adrian P. Sep 6 '13 at 16:44
42  
@GabrielFlorit No splice modifies the array. splice != slice. – Bleeding Fingers Apr 4 '14 at 18:24

I made a fairly efficient extension to the base javascript array:

Array.prototype.drop = function(k) {
  var valueIndex = this.indexOf(k);
  while(valueIndex > -1) {
    this.removeAt(valueIndex);
    valueIndex = this.indexOf(k);
  }
};
share|improve this answer

Too old to reply, but may it help someone, by providing a predicate instead of a value.

Definition

var ArrayHelper = {

    // Remove and return the first occurrence     

    remove: function(array, predicate) {
        for (var i = 0; i < array.length; i++) {
            if (predicate(array[i])) {
                return array.splice(i, 1);
            }
        }
    },

    // Remove and return all occurrences  

    removeAll: function(array, predicate) {
        var removed = [];

        for (var i = 0; i < array.length;) {

            if (predicate(array[i])) {
                removed.push(array.splice(i, 1));
                continue;
            }

            i++;                
        }

        return removed;
    }
};

Usage

ArrayHelper.remove(myArray, row => row.id === 5 );
ArrayHelper.removeAll(myArray, row => row.name.startsWith('BMW'));
share|improve this answer
    
I don't know that you need the -1 check (i > -1). Also, I think these functions act more like filter than remove. If you pass row.id === 5, it will result in an array with only id 5, so it is doing the opposite of remove. It would look nice in ES2015: var result = ArrayHelper.remove(myArray, row => row.id === 5); – What Would Be Cool Sep 20 '15 at 19:42
    
@WhatWouldBeCool this function modify the original array, and return the removed item instead of copying the result to a new array – Ahmad Sep 21 '15 at 7:21

use jQuery.grep()

var y = [1, 2, 3, 9, 4]
var removeItem = 9;

y = jQuery.grep(y, function(value) {
  return value != removeItem;
});
console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

share|improve this answer
    
The OP specifically said no frameworks. Hence the downvote. – user567 Aug 6 at 9:56

Vanilla JavaScript

Browser support: Internet Explorer 9 or later (detailed browser support)

/**
 * Remove item from array
 *
 * Modifies the array “in place”, i.e. the array passed as an argument
 * is modified as opposed to creating a new array. Also returns the modified
 * array for your convenience.
 */
function removeFromArray(array, item) {
    var itemIndex;

    // Look for the item (the item can have multiple indices)
    itemIndex = array.indexOf(item);

    while (itemIndex !== -1) {
        // Remove the item, then return the modified array
        array.splice(itemIndex, 1);

        itemIndex = array.indexOf(item);
    }

    // Return the modified array
    return array;
}
share|improve this answer

The following method will remove all entries of a given value from an array without creating a new array and with only one iteration which is superfast. And it works in ancient Internet Explorer 5.5 browser:

function removeFromArray(arr, removeValue) {
  for (var i = 0, k = 0, len = arr.length >>> 0; i < len; i++) {
    if (k > 0)
      arr[i - k] = arr[i];

    if (arr[i] === removeValue)
      k++;
  }

  for (; k--;)
    arr.pop();
}

var a = [0, 1, 0, 2, 0, 3];

document.getElementById('code').innerHTML =
  'Initial array [' + a.join(', ') + ']';
//Initial array [0, 1, 0, 2, 0, 3]

removeFromArray(a, 0);

document.getElementById('code').innerHTML +=
  '<br>Resulting array [' + a.join(', ') + ']';
//Resulting array [1, 2, 3]
<code id="code"></code>

share|improve this answer
    
What is meaning of this code I could not understand. – Ankur Loriya Dec 17 '15 at 14:22
    
@AnkurLoriya This code removes all 0s from the given array – Eugene Tiurin Dec 25 '15 at 19:16

Remove last occurrence or all occurrences, or first occurrence?

var array = [2, 5, 9, 5];

// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Remove this line to remove all occurrences
  }
}

or

var array = [2, 5, 9, 5];

// Remove first occurrence
for (var i = 0; array.length; i++) {
  if (array[i] === 5) {
     array.splice(i, 1);
     break; // Do not remove this line
  }
}
share|improve this answer

By my solution you can remove one or more than one item in an array thanks to pure JavaScript. There is no need for another JavaScript library.

var myArray = [1,2,3,4,5]; // First array

var removeItem = function(array,value) {  // My clear function
    if(Array.isArray(value)) {  // For multi remove
        for(var i = array.length - 1; i >= 0; i--) {
            for(var j = value.length - 1; j >= 0; j--) {
                if(array[i] === value[j]) {
                    array.splice(i, 1);
                };
            }
        }
    }
    else { // For single remove
        for(var i = array.length - 1; i >= 0; i--) {
            if(array[i] === value) {
                array.splice(i, 1);
            }
        }
    }
}

removeItem(myArray,[1,4]); // myArray will be [2,3,5]
share|improve this answer

A more modern, ECMAScript 2015 (formerly known as Harmony or ES 6) approach. Given:

const items = [1, 2, 3, 4];
const index = 2;

Then:

items.filter((x, i) => i !== index);

Yielding:

[1, 2, 4]

You can use Babel and a polyfill service to ensure this is well supported across browsers.

share|improve this answer
    
Note that .filter returns a new array, which is not exactly the same as removing the element from the same array. The benefit of this approach is that you can chain array methods together. eg: [1,2,3].filter(n => n%2).map(n => n*n) === [ 1, 9 ] – CodeOcelot May 6 at 18:58
    
Great, if I have 600k elements in array and want to remove first 50k, can you imagine that slowness? This is not solution, there's need for function which just remove elements and returns nothing. – Seraph May 30 at 15:11
    
@Seraph For that, you'd probably want to use splice or slice. – bjfletcher May 31 at 22:04
    
@bjfletcher Thats even better, in process of removal, just allocate 50K elements and throw them somewhere. (with slice 550K elements, but without throwing them from the window). – Seraph May 31 at 23:06

I think many of the JavaScript instructions are not well thought out for functional programming. Splice returns the deleted element where most of the time you need the reduced array. This is bad.

Imagine you are doing a recursive call and have to pass an array with one less item, probably without the current indexed item. Or imagine you are doing another recursive call and has to pass an array with an element pushed.

In neither of these cases you can do myRecursiveFunction(myArr.push(c)) or myRecursiveFunction(myArr.splice(i,1)). The first idiot will in fact pass the length of the array and the second idiot will pass the deleted element as a parameter.

So what I do in fact... For deleting an array element and passing the resulting to a function as a parameter at the same time I do as follows

myRecursiveFunction(myArr.slice(0,i).concat(a.slice(i+1)))

When it comes to push that's more silly... I do like,

myRecursiveFunction((myArr.push(c),myArr))

I believe in a proper functional language a method mutating the object it's called upon must return a reference to the very object as a result.

share|improve this answer
Array.prototype.remove = function(x) {
    var y=this.slice(x+1);
    var z=[];
    for(i=0;i<=x-1;i++) {
        z[z.length] = this[i];
    }

    for(i=0;i<y.length;i++){
        z[z.length]=y[i];
    }

    return z;
}
share|improve this answer

The easiest way:

var index = array.indexOf(item);
if(index != -1)
    array.splice( index, 1 );
share|improve this answer

Be careful when you use delete for an array. It is good for deleting attributes of objects but not so good for arrays. It is better to use splice for arrays.

Keep in mind that when you use delete for an array you could get wrong results for anArray.length. In other words, delete would remove the element but wouldn't update the value of length property.

You can also expect to have holes in index numbers after using delete, e.g. you could end up with having indexes 1,3,4,8,9,11 and length as it was before using delete. In that case, all indexed for loops would crash, since indexes are no longer sequential.

If you are forced to use delete for some reason, then you should use for each loops when you need to loop through arrays.

share|improve this answer

If you have complex objects in the array you can use filters? In situations where $.inArray or array.splice is not as easy to use. Especially if the objects are perhaps shallow in the array.

E.g. if you have an object with an Id field and you want the object removed from an array:

this.array = this.array.filter(function(element, i) {
    return element.id !== idToRemove;
});
share|improve this answer
    
This is how I like to do it. Using an arrow function it can be a one-liner. I'm curious about performance. Also worth nothing that this replaces the array. Any code with a reference to the old array will not notice the change. – joeytwiddle Jul 29 at 8:50

Remarks

  • This function removes every occurence of specified value from array.
  • Function name have "stackoverflow_" prefix to prevent name collision. If you accepts the risk of name collision, you can remove that prefix.
  • There are described 4 versions of this function for different cases.

Option #1 Extending "Array.prototype" with "Object.defineProperty" function

Compatible browsers: Internet Explorer 9+, Firefox 4+, Chrome 5+, Safari 5+, and Opera 12+

Extend the Array prototype by using "Object.defineProperty" function.

This approach will not cause problems with enumeration, because we marked "enumerable" as "false".

Be sure that your browser supports "Object.defineProperty" function. Here is the compatibility table:

http://kangax.github.io/es5-compat-table/#Object.defineProperty

Extension code:

// Extending Array prototype with new function,
// if that function is already defined in "Array.prototype", 
// then "Object.defineProperty" will throw an exception
Object.defineProperty(Array.prototype, "stackoverflow_remove", {
    // Specify "enumerable" as "false" to prevent function enumeration
    enumerable: false,

    /**
    * Removes all occurence of specified item from array
    * @this Array
    * @param itemToRemove Item to remove from array
    * @returns {Number} Count of removed items
    */
    value: function (itemToRemove) {
        // Count of removed items
        var removeCounter = 0;

        // Iterate every array item
        for (var index = 0; index < this.length; index++) {
            // If current array item equals itemToRemove then
            if (this[index] === itemToRemove) {
                // Remove array item at current index
                this.splice(index, 1);

                // Increment count of removed items
                removeCounter++;

                // Decrement index to iterate current position 
                // one more time, because we just removed item 
                // that occupies it, and next item took it place
                index--;
            }
        }

        // Return count of removed items
        return removeCounter;
    }
});

Usage code #1:

var arr = [1, 2, 3, 2, 2, 2];

var itemsRemoved = arr.stackoverflow_remove(2);

console.log(itemsRemoved);
// 4

console.log(arr);
// [1, 3]

Usage code #2:

var arr = ["tree", "bird", "car", "bird", "bird"];

var itemsRemoved = arr.stackoverflow_remove("bird");

console.log(itemsRemoved);
// 3

console.log(arr);
// ["tree", "car"]


Option #2 Defining global function. For old browsers which not support prototype extending with "Object.defineProperty"

If you want to use this function without "Object.defineProperty", you can define it as a global scope function.

Extension code:

/**
* Removes all occurence of specified item from array
* @param array Array
* @param itemToRemove Item to remove from array
* @returns {Number} Count of removed items
*/
function stackoverflow_removeArrayItem(array, itemToRemove) {
    // Count of removed items
    var removeCounter = 0;

    // Iterate every array item
    for (var index = 0; index < array.length; index++) {
        // If current array item equals itemToRemove then
        if (array[index] === itemToRemove) {
            // Remove array item at current index
            array.splice(index, 1);

            // Increment count of removed items
            removeCounter++;

            // Decrement index to iterate current position 
            // one more time, because we just removed item 
            // that occupies it, and next item took it place
            index--;
        }
    }

    // Return count of removed items
    return removeCounter;
}

Usage code:

var arr = ["tree", "bird", "car", "bird", "bird"];

var itemsRemoved = stackoverflow_removeArrayItem(arr, "bird");

console.log(itemsRemoved);
// 3

console.log(arr);
// ["tree", "car"]


Option #3 For high performance

This code uses a "filter" function and it works about 50 times faster than previous options, but this approach creates new array.

Extension code:

// Extending Array prototype with new function,
// if that function is already defined in "Array.prototype", 
// then "Object.defineProperty" will throw an exception
Object.defineProperty(Array.prototype, "stackoverflow_filterValue", {
    // Specify "enumerable" as "false" to prevent function enumeration
    enumerable: false,

    /**
    * Create new array where specified item is removed
    * @this Array
    * @param itemToRemove Item to remove from array
    * @returns {Number} Count of removed items
    */
    value: function (itemToRemove) {
        var filteredArray = this.filter(function(item){
            return item !== itemToRemove;
        });

        return filteredArray;
    }
});

Usage code:

var arr = [1, 2, 3, 2, 2, 2];

// PAY ATTENTION.
// Original array stay unchanged.
var filteredArray = arr.stackoverflow_filterValue(2);

console.log(filteredArray);
// [1, 3]

Option #4 ECMAScript 2015 way (if your browser support modern JavaScript or you use Babel.js)

Using new version of JavaScript we need no custom functions to remove array items. Using only filter(...) function and arrow function we got very tiny code:

let value = 3;

let arr = [1, 2, 3, 4, 5, 3];

arr = arr.filter(item => item !== value);

console.log(arr); 
// [ 1, 2, 4, 5 ]
share|improve this answer
4  
The risk you run when you add methods to built-in prototypes is that a future version of JavaScript will implement a method with the same name, and then your code will break any scripts that depend on the built-in behavior, or your scripts will break because your API may not be compatible with the built-in API. – Eric Elliott Nov 18 '14 at 18:16
    
Eric, just add prefix to function name that specifies, that it is custom function. This will prevent collision. – Ujeenator Nov 25 '14 at 15:23
1  
Amber, 1) Nice idea, but few people actually do that. (See your answer for proof). 2) Even if people did that, what's to prevent different authors from choosing the same prefix? For much better solutions, see jQuery, Underscore, Lodash, Highland.js, etc...: $('#el').newMethod(), _(myArray).filterValue(2), etc... – Eric Elliott Nov 26 '14 at 3:46
3  
The shit risk is this method freezes datepicker (jquery plugin) because somewhere is does use the same method overwritten. Thanks the devil i could find the bug with a nice debugger. I had to rename the method "Object.defineProperty(Array.prototype, "_remove") – Ismael Dec 11 '14 at 16:12

There is no need to use indexOf or splice. However, it performs better if you only want to remove one occurrence of an element.

Find and move (move):

function move(arr, val) {
  var j = 0;
  for (var i = 0, l = arr.length; i < l; i++) {
    if (arr[i] !== val) {
      arr[j++] = arr[i];
    }
  }
  arr.length = j;
}

Use indexOf and splice (indexof):

function indexof(arr, val) {
  var i;
  while ((i = arr.indexOf(val)) != -1) {
    arr.splice(i, 1);
  }
}

Use only splice (splice):

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

Run-times on nodejs for array with 1000 elements (average over 10000 runs):

indexof is approximately 10x slower than move. Even if improved by removing the call to indexOf in splice it performs much worse than move.

Remove all occurrences:
    move 0.0048 ms
    indexof 0.0463 ms
    splice 0.0359 ms

Remove first occurrence:
    move_one 0.0041 ms
    indexof_one 0.0021 ms
share|improve this answer
    
Simple, yet effective – Jake Toronto Feb 5 '15 at 18:11
    
Looks like the 'move' method presented here should work in all browsers, and also avoids creating an extra array; most other solutions here have one or both of these problems. I think this one deserves a lot more votes, even if it doesn't look as "pretty". – sockmonk Jul 29 '15 at 11:50
    
That move function is very clever. – Niko Bellic Aug 27 '15 at 1:26
    
Love this. great answer! – Thatkookooguy Jun 8 at 8:57

You can use lodash _.pull (mutate array), _.pullAt (mutate array) or _.without (does't mutate array),

var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']

var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']

var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
share|improve this answer
    
That's not core JS as the OP requested, is it? – some-non-descript-user Sep 24 '15 at 21:01
3  
@some-non-descript-user You are right. But a lot of users like me come here looking for a general answer not just for the OP only. – Chun Yang Oct 1 '15 at 3:38

If you must support older versions of Internet Explorer, I recommend using the following polyfill (note: this is not a framework). It's a 100% backwards-compatible replacement of all modern array methods (JavaScript 1.8.5 / ECMAScript 5 Array Extras) that works for Internet Explorer 6+, Firefox 1.5+, Chrome, Safari, & Opera.

https://github.com/plusdude/array-generics

share|improve this answer
    
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Krumia May 18 '15 at 3:03
1  
Sadly, the internet (and Stack Overflow) are filled with half-implemented, partially-correct versions of ES5 array methods. That is entirely the point of the linking to the polyfill. For a truly complete reproduction of all of the correct behaviors, it isn't good enough to summarize "the essential parts." You have to implement all of the edge conditions as well. To reproduce their content in its entirety is well beyond the scope of Stack Overflow. Stack Overflow is not GitHub. – Matt Brock May 18 '15 at 13:38

Removing the value with index and splice!

function removeArrValue(arr,value) {
    var index = arr.indexOf(value);
    if (index > -1) {
        arr.splice(index, 1);
    }
    return arr;
}
share|improve this answer
12  
Your 2 last comments were just rewriting an accepted answer... Please answer a solved problem only if you have more information to provide than the accepted one. If not, just upvote the accepted answer. – Miam84 Oct 22 '14 at 14:43

Use jQuery's InArray:

A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`   

Note: inArray will return -1, if the element was not found.

share|improve this answer
4  
but OP said: "good ol' fashioned JavaScript - no frameworks allowed" – CSᵠ Dec 12 '14 at 18:51
    
for Chrome 50.0, A.splice(-1, 1); will remove the last one in A. – Scott 混合理论 Jun 17 at 9:38

A friend was having issues in Internet Explorer 8, and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.

Remove ALL instances from an array

  function remove(arr, item) {
      for(var i = arr.length; i--;) {
          if(arr[i] === item) {
              arr.splice(i, 1);
          }
      }
  }

It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.

share|improve this answer
8  
@sroes it should not be because the loop starts at i = arr.length -1 or i-- making it same as the max index. arr.length is just an initial value for i. i-- will always be truthy (and reducing by 1 at each loop op) until it equals 0 (a falsy value) and the loop will then stop. – gabeno Jan 29 '14 at 20:06
1  
Second function is rather inefficient. On every iteration "indexOf" will start search from beginning of array. – Ujeenator Feb 25 '15 at 13:32
    
@AmberdeBlack, you're exactly right. Surprised I didn't catch that when I answered: jsperf.com/remove-all-from-array – Ben Lesh Mar 3 '15 at 3:12
1  
@AlJey, it's available only from IE9+. There is still a chance that it wouldn't work. – Ujeenator Mar 30 '15 at 16:23
1  
This answer worked for me because I needed several items removed but not in any particular order. The backwards progression of the for loop here handles removing items from the array perfectly. – mintedsky Jul 14 '15 at 23:39

John Resig posted a good implementation:

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

If you don’t want to extend a global object, you can do something like the following, instead:

// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

But the main reason I am posting this is to warn users against the alternative implementation suggested in the comments on that page (Dec 14, 2007):

Array.prototype.remove = function(from, to){
  this.splice(from, (to=[0,from||1,++to-from][arguments.length])<0?this.length+to:to);
  return this.length;
};

It seems to work well at first, but through a painful process I discovered it fails when trying to remove the second to last element in an array. For example, if you have a 10-element array and you try to remove the 9th element with this:

myArray.remove(8);

You end up with an 8-element array. Don't know why but I confirmed John's original implementation doesn't have this problem.

share|improve this answer
    
+1, i was going to add that reference myself :) – Nikos M. Sep 17 '14 at 22:13
    
Just learned by the hard way why it is a good idea to use Object.prototype.hasOwnProperty always ¬¬ – Davi Fiamenghi Apr 11 '15 at 4:58
    
love this implementation! – fauverism Apr 15 '15 at 17:59

There are many fantastic answers here, but for me, what worked most simply wasn't removing my element from the array completely but simply setting the value of it to null. This works for most cases I have, and is a good solution since I will be using the variable later and don't want it gone, just empty for now. Also, this approach is completely cross-browser compatible.

array.key = null;
share|improve this answer
    
Nice thinking! This is dead simple and also works for numeric indices. The main issue is that the index and item (null) remain, so the array doesn't get smaller and iterating over it later takes more time. – Beejor 4 hours ago

I'm pretty new to JavaScript and needed this functionality. I merely wrote this:

function removeFromArray(array, item, index) {
  while((index = array.indexOf(item)) > -1) {
    array.splice(index, 1);
  }
}

Then when I want to use it:

//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];

//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");

Output - As expected. ["item1", "item1"]

You may have different needs than I, so you can easily modify it to suit them. I hope this helps someone.

share|improve this answer

If you want a new array with the deleted positions removed, you can always delete the specific element and filter out the array. It might need an extension of the array object for browsers that don't implement the filter method but in the long term its easier since all you do is 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]

share|improve this answer

In CoffeeScript:

my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value
share|improve this answer

Depends on whether you want to keep an empty spot or not.

If you do want an empty slot, delete is fine:

delete array[ index ];

If you don't, you should use the splice method:

array.splice( index, 1 );

And if you need the value of that item, you can just store the returned array's element:

var value = array.splice( index, 1 )[0];

In case you want to do it in some order, you can use array.pop() for the last one or array.shift() for the first one (and both return the value of the item too).

And if you don't know the index of the item, you can use array.indexOf( item ) to get it (in a if() to get one item or in a while() to get all of them). array.indexOf( item ) returns either the index or -1 if not found. 

share|improve this answer
37  
It's worth noting that var value will not store the removed value but an array containing the removed value. – Jakub Jul 10 '13 at 9:55
10  
delete is not the correct way to remove an element from an array!! – Progo Jul 4 '14 at 14:20
6  
If you want to "empty a slot", use array[index] = undefined;. Using delete will destroy optimisation. – Bergi Aug 11 '14 at 16:40
2  
@Jakub very good comment because to understand that I lost much time and thought my application code is somehow broken... – Pascal Dec 14 '14 at 19:14
var index,
    input = [1,2,3],
    indexToRemove = 1;
    integers = [];

for (index in input) {
    if (input.hasOwnProperty(index)) {
        if (index !== indexToRemove) {
            integers.push(result); 
        }
    }
}
input = integers;

This solution will take an array of input and will search through the input for the value to remove. This will loop through the entire input array and the result will be a second array integers that has had the specific index removed. The integers array is then copied back into the input array.

share|improve this answer
1  
This is very inefficient when the array is large. – Christophe Roussy Sep 25 '14 at 14:40

I like this version of splice, removing an element by its value using $.inArray:

$(document).ready(function(){
    var arr = ["C#","Ruby","PHP","C","C++"];
    var itemtoRemove = "PHP";
    arr.splice($.inArray(itemtoRemove, arr),1);
});
share|improve this answer
    
Removes last item if searched item not found – Hontoni Apr 30 '14 at 17:05
1  
yes correct, you should know which element you want to remove like in the other examples. – mboeckle May 1 '14 at 17:00
    
This is jQuery, not core JavaScript. – Dughall Apr 18 at 15:31
    
Dughall - Thanks you are right. – mboeckle Apr 18 at 19:13

Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older IE it uses its own custom methods.

Simple example to remove elements from array (from the website) -

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
share|improve this answer

protected by Andrew Marshall Dec 15 '14 at 20:00

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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