Jquery : map and grep functions

15 / Nov / 2010 by Amit Jain 0 comments

Hi friends,

I was going through some utility funcitons being provided by jQuery. Found few methods like grep, map very userful that saves me from writing loops. I could relate them with grep, collect respectively as provided by Groovy, thought would share with you.

I will be taking examples with JSON objects say Student.
grep()

var students = [ {'id':1, 'name':'amit'},{'id':2, 'name':'ankit'}];
jQuery.grep(students,function(student){ return student.id>1});

//Output :  [{'id':2, 'name':'ankit'}]

jQuery.grep(students,function(student){ return student.id>1}, true) // invert the results

//Output : [ {'id':1, 'name':'amit'}]

map()

 var students = [ {'id':1, 'name':'amit'},{'id':2, 'name':'ankit'}];
jQuery.map(students,function(student){ return student.name=student.name.toUpperCase()});

//Output : ["AMIT", "ANKIT"]
//Updated students list :  [ {'id':1, 'name':'AMIT'},{'id':2, 'name':'ANKIT'}];


jQuery.map(students,function(student){ return student.greetings="HELLO " + student.name});

//Output : ["HELLO AMIT", "HELLO ANKIT"]
//Updated students list : [ {'id':1, 'name':'AMIT', 'greetings' : 'HELLO AMIT'},{'id':2, 'name':'ANKIT', 'greetings' : 'HELLO ANKIT'}]

Hope this helped.

~~Amit Jain~~
amit@intelligrape.com

Tag -

grep jquery map
FOUND THIS USEFUL? SHARE IT

Leave a comment -