JavaScript: Remove element from Array
[UPDATE] Thanks to Joe and others hinting me to the danger of purely using indexOf() without a check for -1. Added it in the last example.
I mean it’s not the first time I am doing it, but it happens always again that I have to look up how exactly it works. And every time I know it is very easy.
So here is how to remove an element from an array, mainly for my poor brain, so it doesn’t have to remember anymore. Though I know, now that I wrote it down I will never forget it again.
DON’T
Unfortunately the most obvioous solution leaves a “hole” in the array :-(.
>>> var list = [4,5,6];
>>> delete list[1];
true
>>> list
[4, undefined, 6]
Sad, but understandable.
DO
So do it right and use splice().
>>> var list = [4,5,6];
>>> list.splice(1, 1); // Remove one element, returns the removed ones.
[5]
>>> list
[4, 6]
Useful DO
Actually, what I mostly need is: remove a certain value from an array.
I.e. I have some list of visible IDs and I want to remove one because it’s not visible anymore. So just extend the above example a bit.
>>> var visibleIds = [4,5,6];
>>> var idx = visibleIds.indexOf(5); // Find the index
>>> if(idx!=-1) visibleIds.splice(idx, 1); // Remove it if really found!
[5]
>>> visibleIds
[4, 6]
I hope I didn’t bore anyone with that
David Golightly said,
May 20, 2008 at 11:29 pm
Another way to do it would be to track your visible IDs in an object:
>>> var visibleIds = {4: true, 5: true, 6: true};
>>> delete visibileIds[5];
>>> visibleIds
{4:true, 6: true}
since what you want is more like set logic, where no item can appear more than once. Then you can also do membership tests like
>>> 5 in visibleIds
false
The only drawback is, you can only use object literals like this for strings (and things that can be converted to and from string values, like numbers).
Wolfram said,
May 21, 2008 at 10:15 pm
There are too many differences between arrays and objects in JavaScript, so I think the object way is very special and you should really _know_ when and why to use it.
Simple things like .length, .sort() and .reverse() can’t be used, so there is quite a difference, as you are saying.
The set logic kind of thing is true, though we should mention that indexOf() returns the first occurence (if no second parameter, the offset is not given), so it’s only kind of a set logic.
Adam said,
August 31, 2008 at 10:13 pm
Great post, looked through three other google results with no luck. Got exactly what I needed here in just two minutes. Thanks again!
Francesco said,
September 22, 2008 at 12:38 pm
Thanks for this solution
Sjoe said,
October 21, 2008 at 11:51 am
Thanks, just what I needed!
Zeal said,
October 29, 2008 at 12:20 pm
Many thanks for it!
Makwana Sachin said,
November 19, 2008 at 7:33 pm
thanks a lot
great solution
pjohndavid said,
November 26, 2008 at 4:57 pm
That was great and simple… thanks!
lp1051 said,
December 7, 2008 at 1:13 am
indexOf() method not supported on arrays in IE6 (don\’t know how 7+), but good tip anyway
Samira said,
December 26, 2008 at 5:43 pm
Thanks alot.
akin said,
January 16, 2009 at 4:56 pm
“I hope I didn’t bore anyone with that ”
nope man, never! instead it was a joy finding and reading this helpful post
Randeep said,
January 28, 2009 at 8:06 pm
Very useful - ta.
Mamoon ur Rasheed said,
May 11, 2009 at 7:58 pm
ROCK ON
adam said,
May 21, 2009 at 3:39 pm
Thanks!
Do Nam Khanh said,
May 27, 2009 at 10:42 am
Thanks for your post
tony said,
June 2, 2009 at 4:34 pm
thanks! just what i needed
haydar said,
July 9, 2009 at 2:41 pm
thanks you very much
because i seach about one hour
I love it
nguyen said,
July 26, 2009 at 10:05 am
thanhks
aal said,
September 8, 2009 at 5:23 pm
great way to do it, too bad it doesn’t work in IE6.. i still have to support that browser
msbrogli said,
October 23, 2009 at 5:31 am
aal, indexOf is not implemented in IE6. So, you could just do it:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf(value, start) {
var i;
if (!start) {
start = 0;
}
for(i=start; i<this.length; i++) {
if(this[i] == value) {
return i;
}
}
return -1;
}
}
Now, it works still in IE6
msbrogli said,
October 23, 2009 at 5:32 am
Sorry…
the correct is: Array.prototype.indexOf: function(value, start)
hehehe
Kent said,
November 24, 2009 at 10:16 pm
Wow. I wish all code tips were like this- short, to the point, and works perfectly!
Oldfield said,
November 26, 2009 at 6:16 am
Simple and nice THANK YOU
C Houghton said,
December 1, 2009 at 8:12 am
Array.prototype.indexOf: function(value, start)
should be
Array.prototype.indexOf = function(value, start)
Joe T. said,
December 10, 2009 at 9:02 pm
Array.indexOf returns -1 when a value is not found in the array. If the offset (first argument) of splice() is negative, the splice begins at the end of the array and moves in reverse:
var arr = [ 3, 4, 5, 6 ];
arr.splice(arr.indexOf(7), 1);
// arr.indexOf(7) == -1, or [ 6 ] from the array
// arr is now [ 3, 4, 5 ];
arr.splice(arr.indexOf(7), 2);
// arr is now [ 3 ];
Use this shortcut with caution!
JungleCoder said,
April 20, 2010 at 7:08 am
nice quick reference and clear explanation, thanks for posting.
also, like the “pythoneer” title, cool
DizzyC said,
April 27, 2010 at 9:10 am
Thanks, useful info. Found it on a quicksearch and it was exactly what i needed.
btopro said,
July 2, 2010 at 7:53 pm
exactly what I was looking for, thanks!
Ventzy said,
July 13, 2010 at 4:23 pm
Wolfram, see Joe T. comment and at least make a note in your code, because if element is not found, last element from the array is removed, which is plain wrong.
Wolfram said,
July 14, 2010 at 4:04 pm
Thanks Ventzy and Joe for pointing it out, I fixed it.
adrian said,
October 14, 2010 at 7:11 am
how bout removing an object in array?
arr = [{1:'country'},{2:'zone'},{3:'area'}];
how can i remove {2:’zone’} and make it?
arr = [{1:'country'},{3:'area'}];
is there a quicker way instead of doing a loop?
plr store said,
October 22, 2010 at 12:57 pm
Useful piece of code, but this method works as well, to remove an element from the array if the value is known but key is not known.
var arr = [];
var val = “sth”;
for(i in arr){
if(arr[i].indexOf(val)>-1){
delete arr[i];
}
}
Darren said,
November 20, 2010 at 7:19 pm
@plr store Thanks for the code.
Unfortunately, the “delete arr[i];” in your code leaves an “undefined” space where the original element was.
I replaced this line with “array.splice(i–, 1);” and it works fine.
Here is the complete code I am using:
function removeFromArray(string, array)
{
for(i in array)
{
if(array[i].indexOf(string)>-1)
{
array.splice(i–, 1);
}
}
return array;
}
Mark said,
February 16, 2011 at 1:22 pm
Nearly 3 years after the original post, and it helped me out! cheers man!
tyler said,
March 3, 2011 at 1:39 am
Thank you!
Aamir Afridi said,
March 8, 2011 at 3:48 pm
Thats exactly what i was looking for. Thanks
José Antonio Arzate said,
March 22, 2011 at 11:20 pm
Excelente!!!
Haseeb said,
April 18, 2011 at 12:09 pm
Thanx a lot
Got What I needed
vijay pratap said,
April 20, 2011 at 1:58 pm
Thanx a lot………
Mr.Xprt said,
May 21, 2011 at 9:36 pm
Great Work .
thanks
krritter said,
June 16, 2011 at 5:22 pm
what if I want to remove (with no spaces left) every element in my array that includes the letters “CE” anywhere in the element?
greenfir3 said,
June 18, 2011 at 5:21 am
@krritter
This is how you can remove any element with CE anywhere in it.
It is likely I have the Regular Expression incorrect, I’m no expert on it.
// Create an array of test strings
var myArray = (”none,CE,test CE,CECE,ABCDE,ABCED”).split(”,”);
// Create Regular Expression Pattern
var pattern = /(?:CE)+/;
console.log(myArray);
// Output: [none,CE,test CE,CECE,ABCDE,ABCED]
// This is the important bit
for (var i = 0; i < myArray.length;) {
if (pattern.test(myArray[i])) {
myArray.splice(i, 1);
} else {
i += 1;
}
}
console.log(myArray);
// Output: [none,ABCDE]
Geert said,
November 2, 2011 at 2:13 pm
Thanks a lot!
Wolfram said,
November 2, 2011 at 3:05 pm
very welcome
discount bedroom furniture said,
December 11, 2011 at 12:18 am
I like the valuable information you provide in your articles. I’ll bookmark your weblog and check again here frequently. I am quite certain I will learn plenty of new stuff right here! Best of luck for the next!
Rodolfo Jorge Nemer Nogueira said,
December 29, 2011 at 3:26 pm
Thx you my friend. You saved my day.
Rodolfo Nogueira
UFPR Música - Curitiba Paraná
Brian Dawkins Authentic Jersey said,
January 12, 2012 at 9:19 am
Hey, I had been looking on this subject for a extended although but I was not in a position to discover wonderful resources like that. Now I feel quite confidence by your suggestions about that, I feel you might have choosen a terrific approach to write some info on this topic.
bderooms said,
January 13, 2012 at 2:07 am
!! don’t use it is quite a strong statement.
Personally I don’t like splice since it has side effects.
Better is to check for empty elements and put your next element on the empty spot to fill up the holes. For example I have a map in which I want to remove some elements… Or I loop over the arrya to remove some elements..
Auch… it’ll crash since ur adapting ur arraywhile ur running over it and
will probably get out of memory.
Thnks said,
January 13, 2012 at 11:57 am
Thnks so much!!
Graig Ebersold said,
January 17, 2012 at 1:11 am
Hey! Someone in my Myspace group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Fantastic blog and outstanding style and design.
Dan said,
March 18, 2012 at 2:22 pm
Thanks! Very useful post, saved me a late night.
Claudio said,
April 6, 2012 at 3:36 pm
Thanks!! Quick and Easy way of doing it! Pretty Straightforward”
hermes shop online said,
April 13, 2012 at 10:11 pm
We’re a group of volunteers and starting a new scheme in our community. Your site provided us with helpful information to paintings on. You have done an impressive activity and our entire community can be grateful to you.
Austin Stoney said,
April 17, 2012 at 2:04 pm
The Key Of Getting The Best Rate For Your HDMI cable. This HDMI cable are truly excellent, it has a great number of functions and features.
Chad Walker said,
June 13, 2012 at 5:09 pm
@bedrooms, he never iterated over the array in the example, he used .indexOf(). If you want to splice in an iterator like Array’s forEach() you can do it like this:
var arr = [4, 5, 6];
arr.forEach(function (item, index, arr) {
if (item === 5) {
arr.splice(index, 1);
}
});
The ‘arr’ in the lambda is a clone of the original arr, and at the end of the forEach, the original gets its length and all elements set to the clone’s length and elements.
Of course not all browsers Array implement forEach so:
if (!Array.prototype.forEach) {
// augment the Array prototype with a forEach that conforms
// to ECMAScript5
// iterator - a function with signature (item, index, array)
// context - an optional context to call the iterator, ‘this’
// will be set to it inside of the iterator
Array.prototype.forEach = function (iterator, context) {
var arr = (new Array()).concat(this); // clone this
var i;
for(i = 0; i < this.length; i++) { // iterate over this, but use the clone
iterator.call(context, arr[i], i, arr);
}
this.length = arr.length; // reset this to the clone’s items
for(i = 0; i < this.length; i++) {
this[i] = arr[i];
}
};
}
(since it looks like comments loose white space formatting you can see the example better in this gist: https://gist.github.com/2924672
Bikush said,
August 16, 2012 at 4:42 pm
Here is another idea:
var x = [1,2,3,4,5];
var toRemove = 3;
x = x.filter( function(elem){ return elem!==toRemove; }
It could be turned into function or added to prototype:
Array.prototype.remove = function(target){
return this.filter( function(elem){ return elem!==target; } )
};
Now its x = x.remove(3);
Jquery ajax tutorial said,
October 22, 2012 at 1:15 am
Can I actually uncover you may be from Queensland?
You truly seem like a Foreign :2)
OliverAnthony said,
December 10, 2012 at 7:45 am
We were lucky enough to be able to view the Chanel Spring 2013 collection when it made its rounds in the brand’s NYC offices late last month.
cheap chanel
Chanel Outlet
chanel bags outlet
cheap Chanel 2.55 handbags sale
cheap Chanel 2.55 handbags
discount Chanel 2.55 bags
Chanel Totes
Chanel Totes
cheap Chanel Bowling handbags