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 ?
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.
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.
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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With