Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  141] [ 4]  / answers: 1 / hits: 192187  / 13 Years ago, mon, august 22, 2011, 12:00:00

My situation:



var id_tag = [1,2,3,78,5,6,7,8,47,34,90];


I would like to delete where id_tag = 90 and to return:



var id_tag = [1,2,3,78,5,6,7,8,47,34];


How can I do that?


More From » arrays

 Answers
45

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.


[#90500] Friday, August 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;