Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep vs Filter in jQuery?

Tags:

jquery

filter

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 ?

like image 360
Royi Namir Avatar asked Apr 13 '12 11:04

Royi Namir


People also ask

What is grep in jQuery?

The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.

What does filter do in jQuery?

jQuery filter() Method The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

How do you filter an array in JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


2 Answers

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.

like image 70
omerkirk Avatar answered Sep 27 '22 15:09

omerkirk


Filter is part of jQuery.fn so it's aim is to be used with selector $('div').filter where grep is a jQuery tool method (jQuery.grep)

like image 25
GillesC Avatar answered Sep 27 '22 16:09

GillesC