Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Playing Around with LINQ for JavaScript

5.00/5 (7 votes)
18 Jun 2015CPOL1 min read 23.2K   139  
Playing around with LINQ for JavaScript

One of the more awesome things I like about being a .NET developer is LINQ. LINQ (Language Integrated Query) is a fluent query interface implemented in the .NET framework. It helps you query, sort and order any type of collection. Below you’ll see an example how to sort an array with integers:

JavaScript
int[] numbers = new int[]{ 1, 9, 4, 6, 2, 9, 11, 31 };
int[] orderedNumbers = numbers.Order(i => i).ToArray();

This is a very neat way of querying arrays, lists, dictionaries, objects, etc. There is also a near complete implementation of Linq for JavaScript: https://linqjs.codeplex.com/. Playing with and testing out this library was on my list for a very long time. I’ve made 5 examples which run out of the box with Node.js (or io.js). You can also use the library for browser based JavaScript projects.

Example 1: Filtering by File Name

JavaScript
var linq = require("linq");
var fs = require("fs");
//Example 1

//Let's take a look at all the files in Windows' System32 folder
fs.readdir("C:\\Windows\\System32", function(err, files){
	if(err){
		//If there's an error, show it
		console.log(err);
	}
	else{
		//Well, we have an array with file names here. I only want to show all DLL files
		var result = linq.from(files)
					 .where(function(f){
					 	return f.substr(f.length - 3) == "dll"
					 })
					 .toArray();
		console.log(result);
	}
});

Console Output

JavaScript
[ 'accessibilitycpl.dll
  'ACCTRES.dll',       
  'acledit.dll',       
  'aclui.dll',         
  'acmigration.dll',   
  'acppage.dll',       
  'acproxy.dll',       
  'ActionCenter.dll',  
  'ActionCenterCPL.dll'
  'ActionQueue.dll',   
  'ActivationVdev.dll',
  'activeds.dll',      
  'actxprxy.dll',      
  'adhapi.dll',        
  'adhsvc.dll',        
  'AdmTmpl.dll',       
  'admwprox.dll',      
  'adprovider.dll',    
  'adrclient.dll',....

Example 2: Getting the Average and Highest and Lowest Number

JavaScript
var linq = require("linq");

//Example 2
var grades = [4.4, 8.2, 5.6, 7.8, 6.9, 5.0, 9.8, 10.0, 7.9];
//Ok, I have an array of grades, but I want to know the average:

var average = linq.from(grades)
			  .average();
console.log("Average grade: "+average);

//There, easy, right?

//But what's the lowest grade?
var lowestGrade = linq.from(grades)
				  .min();
console.log("Lowest grade: "+lowestGrade);

//And the highest?
var highestGrade = linq.from(grades)
				  .max();
console.log("Highest grade: "+highestGrade);

Console Output

JavaScript
Average grade: 7.28888888888889
Lowest grade: 4.4
Highest grade: 10

Example 3: Taking a Subset of an Array

JavaScript
var linq = require("linq");
//Let's say we have a large array of numbers

var arr = [];
for(var i=0;i<=1000;i++){
	arr.push(i);
}

//and we want 10 numbers from the 500th index. This is how it's done:
var result = linq.from(arr)
			 .skip(500)
			 .take(10)
			 .toArray();
console.log(result);

//Skip, like the name says, skips the first 500 numbers and take "takes" 
//the next 10 numbers from the array

Console Output

JavaScript
[ 500, 501, 502, 503, 504, 505, 506, 507, 508, 509 ]

Example 4: Joining 2 Arrays

JavaScript
var linq = require("linq");

//Let's say we have 2 arrays
var arr1 = ["a", "b"];
var arr2 = ["c", "d"];

//Let's combine these 2 arrays
var result = linq.from(arr1)
			 .concat(arr2)
			 .toArray();
console.log(result);

Console Output

JavaScript
[ 'a', 'b', 'c', 'd' ]

Example 5: Making a Selection Out of an Object Array

JavaScript
var linq = require("linq");

//We have an array with a few objects inside. We only want an array with all names.

var arr = [
	{name: "Duco", country: "Netherlands"},
	{name: "Bill", country: "USA"},
	{name: "Norbert", country: "Belgium"}
];

//We do it like this
var result = linq.from(arr)
			 .select(function(x){
			 	return x.name;
			 })
			 .toArray();
console.log(result);
//There

Console Output

JavaScript
[ 'Duco', 'Bill', 'Norbert' ]

I like this way of working with variables in both C# and JavaScript and I'm going to use it for future projects for sure. You can download the sample code here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)