Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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
44  
If you need to support <IE9 (sigh) then check this SO question regarding indexOf in IE. – Scotty.NET Sep 13 '13 at 7:48
3  
(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
1  
filter method can do what you want. – Salvador Dali Sep 5 '15 at 23:43
1  
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]. – DevWL May 24 '16 at 23:26
2  
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 '16 at 8:55

45 Answers 45

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 '16 at 15:31

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

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
1  
I read that you shouldnt modify an Object you dont own – ThomasP1988 Oct 14 '16 at 9:48

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
    
destroy( [1,2,3,3,3,4,5], 3 ) returns [1,2,3,4,5]]. i should not be incremented when the array is spliced. – Renze de Waal Jan 23 '14 at 17:34
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

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 Aug 21 '16 at 23:03

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
13  
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

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

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

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
3  
The OP specifically said no frameworks. Hence the downvote. – user567 Aug 6 '16 at 9:56

Based on all the answers which were mainly correct and taking into account the best practices suggested (especially not using Array.prototype directly), I came up with the below code. Let me know if there is anything you find wierd. But should be fine:

// Extending the core Array Object
MyArray.prototype = new Array();
MyArray.prototype.constructor= MyArray;

/**
 * New array class constructor
 */
function MyArray() {
    // Constructor code here
}

 /**
  * Excludes a value from array and returns the rest of array 
  * @param  {string/number/boolean} excludedValue Value   which should be removed
  * @return {array}               
  */
 MyArray.prototype.without = function(excludedValue) { 

    var valueType = typeof excludedValue;

    if (this.length < 1)
        return [];

    if (valueType == 'object' || valueType == 'array' || valueType == 'undefined')
        throw "Argument can not be object, array or undefined";

    for (var index in this) {

            if (this[index] === excludedValue) {

                this.splice(index, 1);
                index--;

            }   
    }; 

    return this;
};

// How to use
var arr = new MyArray();
arr = [1,2,3,4,5,"name", false];

arr.without(1); // will change the array to [2,3,4,5,"name", false]
arr.without("name"); // will change the array to [2,3,4,5, false]
arr.without(false); // will change the array to [2,3,4,5]
arr.without([1,2]); // will throw error as argument can not be array
arr.without({bar: "foo"}); // will throw error as argument can not be object

After two years of coding I now have a more preferred solution as below:

function arrayWithout(arr, values) {
  var isArray = function(canBeArray) {
    if (Array.isArray) {
      return Array.isArray(canBeArray);
    }
    return Object.prototype.toString.call(canBeArray) === '[object Array]';
  };

  var excludedValues = (isArray(values)) ? values : [].slice.call(arguments, 1); 

  for (var i = arr.length - 1; i >= 0; i--) {
    if (excludedValues.indexOf(arr[i]) > -1) {
      arr.splice(i, 1);
    }
  }

  return arr;
}
share|improve this answer
    
I don't know why you got downvoted, I like your approach. It doesn't always have to be a one liner. – Johannes Stadler Jun 24 '16 at 10:22

While most of the answers above answer the question, it is not clear enough why the slice() method has not been used. Yes, filter() meets the immutability criteria, but how about doing the following shorter equivalent:

const myArray = [1,2,3,4];

And now lets say that we should remove the second element from the array, we can simply do: const newArray = myArray.slice(0,1).concat(myArray.slice(2,4)); // [1,3,4]

This way of deleting an element from an array is strongly encouraged today in the community due to its simple and immutable nature. In general, methods which cause mutation should be avoided. For example, you are encouraged to replace push() with concat() and splice() with slice()

share|improve this answer

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
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 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

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.