jQuery Tip: Finding, Adding, and Removing Values from Arrays

JavaScript , jQuery Add comments

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); }

5 responses to “jQuery Tip: Finding, Adding, and Removing Values from Arrays”

  1. Abe Says:
    Great clarity, thankyou for the post
  2. Todd Says:
    Thank you. Right to the point.
  3. Sarah Says:
    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;
    }
  4. Junaid Says:
    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.
  5. Sachin Says:
    Thanks.. nice post

Leave a Reply