Thursday, May 14, 2009

Filter javascript array items with jquery

In JQuery there's a function that allows us to filter specific items of an array:

var test = ["pineaple","apple","strawberry"];
var test_changed = $.grep(array, function(n, i) { return n!="apple"; });

The test_changed array would only contain the pineaple and the strawberry item.

Dismitify:

The parameters of the $.grep function are:
First parameter is the array you want to manipulate
Second parameter is the function that executes the filter on the array (returns true for that item to remain and false for that item to be excluded. The function is called for each item of the array).
This filtering function gets two parameters:
The first one is the current array item (current of the iteration)
The second one is the current array position (aka index).

I hope this is useful for you as it was for me!

Be back soon!

2 comments:

Angelo said...
This comment has been removed by a blog administrator.
Pedro said...

Boa iniciativa, agora acho que como bom portugues, a lingua devia ser em PT abra├žo