Friday, November 18, 2011

linq js

In JavaScript (even with other framework library), there may not be some very easy dot notation way to filter data.

You often have to go through the whole collection then to push values into another array object to collect the values that you want, filtering. 

Data Structure
[ FieldName : string, Filters :  [ IsSelected : boolean, Value : variant  ] ]

Typical JavaScript Filtering Pattern
var data = fetchData(); // gets the ajax data in Json array
var filteredData = new Array(); // where new filtered 
var filterListLimit = getFilteredListLimit(); // number of times which the category changes


/// this is O(n^2) ~= f(x) = O * nO 
for (var q = 0; q < data.length; q++) {
var oX = data[q]; // for convenience
var includeCounter = 0;

for (var f = 0; f < FilterList.length; f++) {
if (oX[FilterList[f][0]] == FilterList[f][1]) {
includeCounter++;
}
}
if (includeCounter == filterListLimit) {
filteredData.push(oX);
}
}

In C#, you can do 
var filteredData =( from p in data
where p.key == 5
select new {
   Brand = p.Brand,
   Name = p.Name,
   Year = new DateTime(p.Date).Year
}).Distinct();

with linq.js, you can do
var filteredData = Enumerable.From(data)
.Where(function(x) { return ( x.key == 5 ) })
.Select("o=> { Brand : o.Brand, Name : o.Name, Year : o.Year "}).Distinct().ToArray();

Neat ... :-)

There are more examples and a file at the below link.

No comments: