Snippets – Filtering JSON Using jQuery Grep, Filter, Map
When you have a JSON array, you may want to get one or more items from the array and display. jQuery offers two functions that can help: grep and filter.
- $.grep(). Finds the elements of an array which satisfy a filter function. The original array is not affected.
- $filter(). Reduce the set of matched elements to those that match the selector or pass the function’s test.
- $.map(). applies a function to each item in the array, thus returning a modified array
In other words, $.grep() removes items from an array as necessary so that all remaining items pass a provided test; .filter() constructs a new jQuery object from a subset of the matching elements.
Also, filter 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.
Continue reading “Snippets – Filtering JSON Using jQuery Grep, Filter, Map”