Aug 30
2009
2009
Usually, finding a particular value in a Javascript array requires looping through the array until you find the value you're looking for.
jQuery provides a utility function called inArray() that takes the value being sought and the array as parameters and returns the index value indicating where in the array the value is located (-1 is returned if the value is not found in the array):
var index= jQuery.inArray(theValue, theArray);
You can use this jQuery function in conjunction with the Javascript push() and slice() functions to easily add or remove a value from an array:
//If you're not using any other Javascript library that utilizes the $ sign, you can use the $ sign
//instead of the jQuery namespace var index= $.inArray(theValue, theArray); if(index== -1) { //Value not found in the array. Add to the end of the array with push(); theArray.push(theValue); } else { //Remove from the array using splice(). Splice takes the index value of where you want to start
//removing items from the array as the first parameter, and then the number of item you want
//to remove as the second parameter. theArray.splice(index,1); }
Nov 11, 2010 at 4:49 AM Great clarity, thankyou for the post
Jan 31, 2011 at 9:22 PM Thank you. Right to the point.
Feb 19, 2011 at 3:25 PM I was looking for something to loop the remove to eliminate all instances in the case of multiples. Using your basic instruction, this seems to do the trick:
function removeFromArray(string, array){
while($.inArray(string,array)!=-1){
array.splice($.inArray(string,array), 1);
}
return array;
}
Nov 10, 2011 at 4:03 PM I have already used this function but this tutorial gave a new clarity to my already poor understanding :)
Thanks and keep up the good work.
Jan 24, 2012 at 3:41 AM Thanks.. nice post