How do I remove a particular element from an array in JavaScript?


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



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.



Find the index of the array element you want to remove, then remove that index with splice.



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.



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



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



I don't know how you are expecting array.remove(int) to behave. There are three possibilities I can think of that you might be wanting.



To remove an element of an array at an index i:



If you want to remove every element with value number from the array:



If you just want to make the element at index i no longer exist, but you don't want the indexes of the other elements to change:



In this code example I use "array.filter(...)" function to remove unwanted items from array, this function doesn't change the original array and creates a new one. If your browser don't support this function (e.g. IE before version 9, or Firefox before version 1.5), consider using the filter polyfill from Mozilla.



IMPORTANT ES2015 "() => {}" arrow function syntax is not supported in IE at all, Chrome before 45 version, Firefox before 22 version, Safari before 10 version. To use ES2015 syntax in old browsers you can use BabelJS



An additional advantage of this method is that you can remove multiple items



IMPORTANT "array.includes(...)" function is not supported in IE at all, Chrome before 47 version, Firefox before 43 version, Safari before 9 version and Edge before 14 version so here is polyfill from Mozilla



Try it yourself in BabelJS :)



Reference



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



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



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



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



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. 



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.



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.



There are two major approaches:



splice(): anArray.splice(index, 1);



delete: delete anArray[index];



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. As the matter of fact, always avoid using indexed for loops, if possible. That way the code would be more robust and less prone to problems with indexes.





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



Use indexOf and splice (indexof):



Use only splice (splice):



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.



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



NOTE: it will update the given array, and return affected rows



John Resig posted a good implementation:



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



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



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:



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



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 Internet Explorer versions it uses its own custom methods.



A simple example to remove elements from array (from the website):



You can do it easily with filter method:



This removes all elements from the array and also works faster then combination of slice and indexOf



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:



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



You can use ES6.



Output :



Check out this code. It works in every major browser.



Call this function



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



OK, for example you are having the array below:



And we want to delete number 4, you can simply do the below code:



If you reusing this function, you write a reusable function which will be attached to Native array function like below:



But how about if you are having the below array instead with few [5]s in the Array?



We need a loop to check them all, but easier and more efficient way is using built-in JavaScript functions, so we write a function which use filter like below instead:



Also there are third parties libraries which do help you to do this, like Lodash or Underscore, for more info look at lodash _.pull, _.pullAt or _.without.



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



Then when I want to use it:



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.



Then :



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:



Update: This method is recommended only if you cannot use ECMAScript 2015 (formerly known as ES6). If you can use it, other answers here provide much neater implementations.



This gist here will solve your problem, and also deletes all occurrences of the argument instead of just 1 (or a specified value).



Usage:



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



Then:



Yielding:



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



You should never mutate your array your array. As this is against functional programming pattern. What you can do is create a new array without referencing the array you want to change data of using es6 method filter;



Suppose you want to remove 5 from the array you can simply do it like this.



This will give you a new array without the value you wanted to remove. So the result will be



For further understanding you can read the MDN documentation on Array.filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter



I know there are a lot of answers already, but many of them seem to over complicate the problem. Here is a simple, recursive way of removing all instances of a key - calls self until index isn't found. Yes, it only works in browsers with indexOf, but it's simple and can be easily polyfilled.



Stand-alone function



Prototype method



You can do a backward loop to make sure not to screw up the indexes, if there are multiple instances of the element.



Remove by Index



Function that return a copy of array without the element at index.



Remove by Value



Function that return a copy of array without the Value.



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



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



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.



2017-05-08



Most of the given answers work for strict comparison, meaning that both objects reference the exact same object in memory (or are primitive types), but often you want to remove a non-primitive object from an array that has a certain value. For instance, if you make a call to a server and want to check a retrieved object against a local object.



There are alternative/faster implementations for valuesAreEqual, but this does the job. You can also use a custom comparator if you have a specific field to check (for example, some retrieved UUID vs a local UUID).



Also note that this is a functional operation, meaning that it does not mutate the original array.



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:



Reviewing the above function, despite the fact that it works fine, I realised there could be some performance improvement. Also using ES6 instead of ES5 is a much better approach. To that end, this is the improved code:



How to use:



I am currently writing a blog post in which I have benchmarked several solutions for Array without problem and compared the time it takes to run. I will update this answer with the link once I finish that post. Just to let you know, I have compared the above against lodash's without and in case the browser supports Map, it beats lodash! Notice that I am not using Array.prototype.indexOf or Array.prototype.includes as wrapping the exlcudeValues in a Map or Object makes querying faster! (https://jsperf.com/array-without-benchmark-against-lodash)




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?

Popular posts from this blog

“Thánh nhọ” Lee Kwang Soo chúc thi tốt, sĩ tử Việt Nam... có dám nhận hay không?

Museum on the Mound

眉山市