Grep vs Filter in jQuery?

Royi Namir picture Royi Namir · Apr 13, 2012 · Viewed 55.5k times · Source

I was wondering about the differences between Grep and Filter :

Filter :

Reduce the set of matched elements to those that match the selector or pass the function's test.

Grep :

Finds the elements of an array which satisfy a filter function. The original array is not affected.

ok.

so if I do this in GREP :

var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];

myNewArray= jQuery.grep(arr, function(n, i){
  return (n != 5 && i > 4);
});

I could do also :

 var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];

myNewArray= $(arr).filter( function(n, i){
  return (n != 5 && i > 4);
});

In both situations I still can access to the original array...

so...where is the difference ?

Answer

omerkirk picture omerkirk · Apr 13, 2012

They both function in similar ways however they differ in their usages.

The filter function is intended to be used with html elements, and that is why it is a chainable function that returns a jQuery object and it accepts filters like ":even", ":odd" or ":visible" etc. You can't do that with the grep function, which is intended to be a utility function for arrays.