Monday, October 19, 2009

jQuery Array Deletion

The jQuery javascript toolkit provides several useful utility functions for working with arrays. One wouldn't think that this functionality would be necessary but in the world of javascript, this is often the case because of different browser implementations. The array utility functionality offered by jQuery includes basic array manipulation and searching.

One such searching function is the jQuery.inArray() function. As the name suggests, the function will determine if a specified element exists in a specified array. This utility is indispensable for javascript developers simply because of the amount of code it reduces.

Searching for elements in a javascript array often involves some kind of looping construct. In each iteration, we check if the current element is the desired element. In the case of array element deletion, we do something like this. The example below illustrates how the jQuery.inArray() function compliments the primitive splicing functionality of javascript arrays.
//Example; jQuery array deletion.

//Make the array.
var my_array=jQuery.makeArray(["A", "B", "C"])

//Find an element to delete.
var my_pos=jQuery.inArray("B", my_array);

//Delete the element only if it exists.
my_pos < 0 || my_array.splice(my_pos, 1);
In this example, we use the jQuery.makeArray() function because it returns a true array. It isn't needed but is a good practice regardless. Next, we find the position of the element we want to delete. Finally, if the my_pos value is less than 0, the element wasn't found and nothing happens. Otherwise, we splice the element out of the array. With the help of jQuery, we are able to seek and destroy array elements with two lines of code.