How to use C# LinQ similar method in JavaScript

Below is a simple example to help understand the usage of the code:

var arr = [
 {name: 'a', val:1},
 {name:'b', val:2},
 {name:'c', val:3},
 {name:'d', val:4},
 {name:'e', val:5},
 {name:'f', val:6},
 ];



//jquery map
 var nm = $.map(arr,function(v){
 return v.val;
 });

$("#box").html("jquery map: "+nm);



//array map
 var nm = arr.map(function(v){
 return v.val;
 });
 $("#box2").html("array map: "+nm);



//grep
 var fName = $.grep(arr, function (p) { return p.name == 'f'; })
 .map(function (p) { return p.val; });
 $("#box3").html("grep map: "+fName);



var result = arr.some(function (p) { return p.val>6; });
 $("#box4").html("some: "+result);



var result2 = arr.filter(function (p) { return (p.val<5); })
 .filter(function (q) { return (q.name=='a'); });
 $("#box5").html("filter: "+ JSON.stringify(result2));



var result3 = arr.find(function (p) { return p.name='e'; });
 $("#box6").html("find: "+ JSON.stringify(result3));

Result can be seen here or test it out yourself: http://jsfiddle.net/aL85j/127/

Map – Translate array/object into new array of items. This is something similar to c# ( var value = listofobject.where(x=>x.name).toList();). Getting a list of particular items which you need. It can be use either jquery map ($.map()) or array map (arr.map()).

Grep – Finds the elements of an array which satisfy a filter function. The original array is not affected. This command is similar to .Where() in c# and it will return an array of result base on your criteria.

Some – Return a Boolean as an when your requirement met or not. something similar to c# (.Any()).

Filter – Reduce the set of matched elements to those that match the selector or pass the function’s test. You can add multiple filter as you need to meet your requirements. Is similar to .Where() as well. And it will return you an object instead of an array.

Find – Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. Similar to .Where() and .First() in C#. It will return the object you search for.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s