Javascript - remove an array item by value
If you're going to be using this often (and on multiple arrays), extend the Array object to create an unset function.
Array.prototype.unset = function(value) {
if(this.indexOf(value) != -1) { // Make sure the value exists
this.splice(this.indexOf(value), 1);
}
}
tag_story.unset(56)
I like to use filter:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
// delete where id_tag = 90
id_tag = id_tag.filter(function(x) {
if (x !== 90) {
return x;
}
});
You'll want to use JavaScript's Array splice
method:
var tag_story = [1,3,56,6,8,90],
id_tag = 90,
position = tag_story.indexOf(id_tag);
if ( ~position ) tag_story.splice(position, 1);
P.S. For an explanation of that cool ~
tilde shortcut, see this post:
Using a ~
tilde with indexOf
to check for the existence of an item in an array.
Note: IE < 9 does not support .indexOf()
on arrays. If you want to make sure your code works in IE, you should use jQuery's $.inArray()
:
var tag_story = [1,3,56,6,8,90],
id_tag = 90,
position = $.inArray(id_tag, tag_story);
if ( ~position ) tag_story.splice(position, 1);
If you want to support IE < 9 but don't already have jQuery on the page, there's no need to use it just for $.inArray
. You can use this polyfill instead.
tag_story.splice(tag_story.indexOf(id_tag), 1);