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

LINQ for JavaScript

4.96/5 (140 votes)
6 Apr 2015CPOL5 min read 212.1K   2.2K  
Implementation of .NET Enumerable methods in JavaScript, including Aggregations, Iterations, Predicators, and Selectors.
This article reviews basic LINQ functionalities applied to JavaScript Arrays.
View the project on GitHub to find a comprehensive data-structure and LINQ library in JavaScript.

Introduction

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays. JavaScript built-in API since ECMAScript 5th Edition comes with a very limited set of iteration methods: forEach, every, some, filter, map, reduce and reduceRight.

These methods are not cross-browser, are different from LINQ API and do not cover most of the functionality that come with LINQ. This article covers the implementation of over 30 .NET 4.0 Enumerable methods in JavaScript, including Aggregations, Iterations, Predicators and Selectors to add power and flexibility of LINQ style queries to traditional JavaScript code.

Background

JavaScript does not intrinsically support class inheritance and clumsily supports it through prototype inheritance. It is possible to simulate many class-based features with prototypes in JavaScript. Prototypes provide object-oriented features customary to object-oriented programming language. It means in order to add more functionality to the built-in API, you can extend the prototype of the class.

All Arrays in JavaScript are descended from Array object, and they inherit methods and properties from Array.prototype. Changes to the Array prototype object are propagated to all arrays unless the properties and methods subject to those changes are overridden further along the prototype chain.

In order to add LINQ functionality to JavaScript, all we need to do is to add those methods to Array.prototype object.

For example, JavaScript API does not have union method, however there's concat method with almost the same functionality. By setting Array.prototype.union to built-in concat method, all JavaScript arrays will also have union method:

(the true union method uses the distinct elements from the union of two sequences)

JavaScript
Array.prototype.union = Array.prototype.concat; 

Before you begin

Most of LINQ Methods require EqualityComparer, SortComparer, Predicate or Selector functions to apply to each element in an Array. In .Net this is done by passing a Delegate to the method. For example this is how a Select method might look like in C#:

C#
var someArray = new int[] { 1, 2, 3, 4 };
var otherArray = someArray.Select(t => t * 2);   

In the example above t => t * 2 is a Lambda expression which behaves as an anonymous function (delegate) to multiply each element of the array by 2. However, since JavaScript does not come with Lambda expressions, anonymous functions in JavaScript are defined using function(){ ... }

Here's how LINQ select method might look like in JavaScript:

JavaScript
var someArray = [1, 2, 3, 4];
var otherArray = someArray.select(function (t) { return t * 2 }); 

Here are the default functions of EqualityComparer, SortComparer, Predicate, or Selector:

JavaScript
function DefaultEqualityComparer(a, b) {
    return a === b || a.valueOf() === b.valueOf();
};
 
function DefaultSortComparer(a, b) {
    if (a === b) return 0;
    if (a == null) return -1;
    if (b == null) return 1;
    if (typeof a == "string") return a.toString().localeCompare(b.toString());
    return a.valueOf() - b.valueOf();
};
 
function DefaultPredicate() {
    return true;
};

function DefaultSelector(t) {
    return t;
}; 

JavaScript LINQ Selectors

Select

Projects each element of a sequence into a new form.

JavaScript
Array.prototype.select = Array.prototype.map || function (selector, context) {
    context = context || window;
    var arr = [];
    var l = this.length;
    for (var i = 0; i < l; i++)
        arr.push(selector.call(context, this[i], i, this));
    return arr;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var doubled = arr.select(function(t){ return t * 2 });  // [2, 4, 6, 8, 10] 

SelectMany

Projects each element of a sequence to an array and flattens the resulting sequences into one sequence.

JavaScript
Array.prototype.selectMany = function (selector, resSelector) {
    resSelector = resSelector || function (i, res) { return res; };
    return this.aggregate(function (a, b, i) {
        return a.concat(selector(b, i).select(function (res) { return resSelector(b, res) }));
    }, []);
}; 

Sample:

var arr = [{Name:"A", Values:[1, 2, 3, 4]}, {Name:"B", Values:[5, 6, 7, 8]}];  
var res1 = arr.selectMany(function(t){ return t.Values });  // using default result selector
var res2 = arr.selectMany(function(t){ return t.Values }, function(t, u){ return {Name:t.Name, Val:u}});  // using custom result selector 

Take

Returns a specified number of contiguous elements from the start of a sequence.

JavaScript
Array.prototype.take = function (c) {
    return this.slice(0, c);
};  

 

Sample:

var arr = [1, 2, 3, 4, 5]; 
var res = arr.take(2);  //  [1, 2]  

Skip

Bypasses a specified number of elements in a sequence and then returns the remaining elements.

JavaScript
Array.prototype.skip = function (c) {
    return this.slice(c);
}; 

 

Sample:

var arr = [1, 2, 3, 4, 5]; 
var res = arr.skip(2);  //  [3, 4, 5]   

First

Returns the first element of a sequence.

JavaScript
Array.prototype.first = function (predicate, def) {
    var l = this.length;
    if (!predicate) return l ? this[0] : def == null ? null : def;
    for (var i = 0; i < l; i++)
        if (predicate(this[i], i, this))
            return this[i];
    return def == null ? null : def;
}; 

Sample:

var arr = [1, 2, 3, 4, 5];
var t1 = arr.first(); // 1 
var t2 = arr.first(function(t){ return t > 2 });  // using comparer: 3 
var t3 = arr.first(function(t){ return t > 10 }, 10);  // using comparer and default value: 10 

Last

Returns the last element of a sequence.

JavaScript
Array.prototype.last = function (predicate, def) {
    var l = this.length;
    if (!predicate) return l ? this[l - 1] : def == null ? null : def;
    while (l-- > 0)
        if (predicate(this[l], l, this))
            return this[l];
    return def == null ? null : def;
};   

Sample:

var arr = [1, 2, 3, 4, 5];
var t1 = arr.last(); // 5 
var t2 = arr.last(function(t){ return t > 2 });  // using comparer: 5 
var t3 = arr.last(function(t){ return t > 10 }, 10);  // using comparer and default value: 10  

Union

Produces the set union of two sequences by using the default equality comparer.

JavaScript
Array.prototype.union = function (arr) {
    return this.concat(arr).distinct();
};  

 

Sample:

var arr1 = [1, 2, 3, 4, 5]; 
var arr2 = [5, 6, 7, 8, 9];
var res = arr1.union(arr2);  // [1, 2, 3, 4, 5, 6, 7, 8, 9]  

Intersect

Produces the set intersection of two sequences.

JavaScript
Array.prototype.intersect = function (arr, comparer) {
    comparer = comparer || DefaultEqualityComparer;
    return this.distinct(comparer).where(function (t) {
        return arr.contains(t, comparer);
    });
}; 

 

Sample:

var arr1 = [1, 2, 3, 4, 5]; 
var arr2 = [1, 2, 3]; 
var res = arr1.intersect(arr2);  // [1, 2, 3]  

Except

Produces the set difference of two sequences.

JavaScript
Array.prototype.except = function (arr, comparer) {
    if (!(arr instanceof Array)) arr = [arr];
    comparer = comparer || DefaultEqualityComparer;
    var l = this.length;
    var res = [];
    for (var i = 0; i < l; i++) {
        var k = arr.length;
        var t = false;
        while (k-- > 0) {
            if (comparer(this[i], arr[k]) === true) {
                t = true;
                break;
            }
        }
        if (!t) res.push(this[i]);
    }
    return res;
};  

 

Sample:

var arr1 = [1, 2, 3, 4, 5]; 
var arr2 = [2, 3, 4];
var res = arr1.except(arr2);  // [1, 5] 

Distinct

Returns distinct elements from a sequence by using the default equality comparer to compare values.

JavaScript
Array.prototype.distinct = function (comparer) {
    var arr = [];
    var l = this.length;
    for (var i = 0; i < l; i++) {
        if (!arr.contains(this[i], comparer))
            arr.push(this[i]);
    }
    return arr;
};     

 

Sample:

var arr1 = [1, 2, 2, 3, 3, 4, 5, 5];   
var res1 = arr.distinct();  // [1, 2, 3, 4, 5]

var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:1}];
var res2 = arr2.distinct(function(a, b){ return a.Val == b.Val });  // [{Name:"A", Val:1}] 

Zip

Applies a specified function to the corresponding elements of two sequences, which produces a sequence of the results.

Array.prototype.zip = function (arr, selector) {
    return this
        .take(Math.min(this.length, arr.length))
        .select(function (t, i) {
            return selector(t, arr[i]);
        });
};  

 

Sample:

var arr1 = [1, 2, 3, 4]; 
var arr2 = ["A", "B", "C", "D"];
var res = arr1.zip(arr2, function(a, b){ return {Num:a, Letter:b} });   
// [{Num:1, Letter: "A"},{Num:2, Letter: "B"}, {Num:3, Letter: "C"}, {Num:4, Letter: "D"}]  

IndexOf

Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.

JavaScript
Array.prototype.indexOf = Array.prototype.indexOf || function (o, index) {
    var l = this.length;
    for (var i = Math.max(Math.min(index, l), 0) || 0; i < l; i++)
        if (this[i] === o) return i;
    return -1;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var index = arr.indexOf(2);  // 1 

LastIndexOf

Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.

JavaScript
Array.prototype.lastIndexOf = Array.prototype.lastIndexOf || function (o, index) {
    var l = Math.max(Math.min(index || this.length, this.length), 0);
    while (l-- > 0)
        if (this[l] === o) return l;
    return -1;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5, 3, 4, 5];
var index = arr.lastIndexOf(3);  // 5 

Remove

Removes the first occurrence of a specific object from the Array.

JavaScript
Array.prototype.remove = function (item) {
    var i = this.indexOf(item);
    if (i != -1)
        this.splice(i, 1);
}; 

Sample:

var arr = [1, 2, 3, 4, 5];
arr.remove(2);   // [1, 3, 4, 5]

RemoveAll

Removes all the elements that match the conditions defined by the specified predicate.

JavaScript
Array.prototype.removeAll = function (predicate) {
    var item;
    var i = 0;
    while (item = this.first(predicate)) {
        i++;
        this.remove(item);
    }
    return i;
}; 

Sample:

var arr = [1, 2, 3, 4, 5];
arr.removeAll(function(t){ return t % 2 == 0 });  // [1, 3, 5]  

OrderBy

Sorts the elements of a sequence in ascending order according to a key.

JavaScript
Array.prototype.orderBy = function (selector, comparer) {
    comparer = comparer || DefaultSortComparer;
    var arr = this.slice(0);
    var fn = function (a, b) {
        return comparer(selector(a), selector(b));
    };

    arr.thenBy = function (selector, comparer) {
        comparer = comparer || DefaultSortComparer;
        return arr.orderBy(DefaultSelector, function (a, b) {
            var res = fn(a, b);
            return res === 0 ? comparer(selector(a), selector(b)) : res;
        });
    };

    arr.thenByDescending = function (selector, comparer) {
        comparer = comparer || DefaultSortComparer;
        return arr.orderBy(DefaultSelector, function (a, b) {
            var res = fn(a, b);
            return res === 0 ? -comparer(selector(a), selector(b)) : res;
        });
    };

    return arr.sort(fn);
}; 

 

Sample:

var arr = [{Name:"A", Val:1}, {Name:"a", Val:2}, {Name:"B", Val:1}, {Name:"C", Val:2}];

var res1 = arr.orderBy(function(t){ return t.Name });   

var res2 = arr.orderBy(function(t){ return t.Name }, function(a, b){
    if(a.toUpperCase() > b.toUpperCase()) return 1;
    if(a.toUpperCase() < b.toUpperCase()) return -1;
    return 0;
});        

OrderByDescending

Sorts the elements of a sequence in descending order.

JavaScript
Array.prototype.orderByDescending = function (selector, comparer) {
    comparer = comparer || DefaultSortComparer;
    return this.orderBy(selector, function (a, b) { return -comparer(a, b) });
}; 

Sample:

var arr = [{Name:"A", Val:1}, {Name:"a", Val:2}, {Name:"B", Val:1}, {Name:"C", Val:2}];
var res = arr.orderByDescending(function(t){ return t.Name });   

ThenBy / ThenByDescending

 

Performs a subsequent ordering of the elements in a sequence in ascending/descending order by using a specified comparer. ThenBy and ThenByDescending are defined to extend the output type of OrderBy and OrderByDescending, which is also the return type of these methods. This design enables you to specify multiple sort criteria by applying any number of ThenBy or ThenByDescending methods.

 

Sample:

var arr = [{Name:"A", Val:1}, {Name:"a", Val:2}, {Name:"B", Val:1}, {Name:"C", Val:2}];

var res1 = arr.orderBy(function(t){ return t.Val })
          .thenBy(function(t){ return t.Name });   

var res2 = arr.orderBy(function(t){ return t.Val })
          .thenByDescending(function(t){ return t.Name }); 
 
var res3 = arr.orderByDescending(function(t){ return t.Val })
          .thenBy(function(t){ return t.Name });   

InnerJoin

Correlates the elements of two sequences based on matching keys.

JavaScript
Array.prototype.innerJoin = function (arr, outer, inner, result, comparer) {
    comparer = comparer || DefaultEqualityComparer;
    var res = [];

    this.forEach(function (t) {
        arr.where(function (u) {
            return comparer(outer(t), inner(u));
        })
        .forEach(function (u) {
            res.push(result(t, u));
        });
    });

    return res;
};  

 

Sample:

var arr1 = [{Name:"A", Val:1}, {Name:"B", Val:2}, {Name:"C", Val:3}];

var arr2 = [{Code:"A"}, {Code:"B"}, {Name:"C", Code:"C"}]; 

var res1 = arr1.innerJoin(arr2,
    function (t) { return t.Name },                                      // arr1 selector
    function (u) { return u.Code },                                      // arr2 selector
    function (t, u) { return { Name: t.Name, Val: t.Val, Code: u.Code } });  // result selector

// using custom comparer
var res2 = arr1.innerJoin(arr2,
    function (t) { return t.Name },                                    // arr1 selector
    function (u) { return u.Code },                                    // arr2 selector
    function (t, u) { return { Name: t.Name, Val: t.Val, Code: u.Code } },  // result selector
    function (a, b) { return a.toUpperCase() == b.toUpperCase() });         // comparer     

GroupJoin

Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys.

JavaScript
Array.prototype.groupJoin = function (arr, outer, inner, result, comparer) {
    comparer = comparer || DefaultEqualityComparer;
    return this
        .select(function (t) {
            var key = outer(t);
            return {
                outer: t,
                inner: arr.where(function (u) { return comparer(key, inner(u)); }),
                key: key
            };
        })
        .select(function (t) {
            t.inner.key = t.key;
            return result(t.outer, t.inner);
        });
};  

 

Sample:

var arr1 = [{Name:"A", Val:1}, {Name:"B", Val:2}, {Name:"C", Val:3}];
var arr2 = [{Code:"A"}, {Code:"A"}, {Code:"B"}, {Code:"B"}, {Code:"C"}];  

var res1 = arr1.groupJoin(arr2, 
    function(t){ return t.Name },                     // arr1 selector
    function(u){ return u.Code },                     // arr2 selector
    function(t, u){ return {Item:t, Group:u} }) ;         // result selector  
  
// using custom comparer  
var res2 = arr1.groupJoin(arr2, 
    function(t){ return t.Name },                             // arr1 selector
    function(u){ return u.Code },                             // arr2 selector
    function(t, u){ return {Item:t, Group:u} },                 // result selector 
    function(a, b){ return a.toUpperCase() == b.toUpperCase() });     // comparer 

GroupBy

Groups the elements of a sequence according to a specified key selector function.

JavaScript
Array.prototype.groupBy = function (selector, comparer) {
    var grp = [];
    var l = this.length;
    comparer = comparer || DefaultEqualityComparer;
    selector = selector || DefaultSelector;

    for (var i = 0; i < l; i++) {
        var k = selector(this[i]);
        var g = grp.first(function (u) { return comparer(u.key, k); });

        if (!g) {
            g = [];
            g.key = k;
            grp.push(g);
        }

        g.push(this[i]);
    }
    return grp;
};  

 

Sample:

var arr = [{Name:"A", Val:1}, {Name:"B", Val:1}, {Name:"C", Val:2}, {Name:"D", Val:2}]; 
var res = arr.groupBy(function(t){ return t.Val }); 
// [[{Name:"A", Val:1}, {Name:"B", Val:1}], [{Name:"C", Val:2}, {Name:"D", Val:2}]] 

res.forEach(function(t){ 
    console.log("Key: " + t.key, "Length: " + t.length); 
});   
// Key: 1 Length: 2  
// Key: 2 Length: 2 

ToDictionary

Creates an object from an array according to a specified key selector function.

JavaScript
Array.prototype.toDictionary = function (keySelector, valueSelector) {
    var o = {};
    var l = this.length;
    while (l-- > 0) {
        var key = keySelector(this[l]);
        if (key == null || key == "") continue;
        o[key] = valueSelector(this[l]);
    }
    return o;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5]; 
var dic = arr.toDictionary(function(t){ return "Num" + t }, function(u){ return u });   
// dic = {Num5: 5, Num4: 4, Num3: 3, Num2: 2, Num1: 1} 

JavaScript LINQ Aggregations

Aggregate

Applies an accumulator function over a sequence.

JavaScript
Array.prototype.aggregate = Array.prototype.reduce || function (func, seed) {
    var arr = this.slice(0);
    var l = this.length;
    if (seed == null) seed = arr.shift();

    for (var i = 0; i < l; i++)
        seed = func(seed, arr[i], i, this);

    return seed;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var sum = arr.aggregate(function(a, b){ return a + b }, 0);  // 15   

Min

Returns the minimum value in a sequence of values.

JavaScript
Array.prototype.min = function (s) {
    s = s || DefaultSelector;
    var l = this.length;
    var min = s(this[0]);
    while (l-- > 0)
        if (s(this[l]) < min) min = s(this[l]);
    return min;
};  

Sample:

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
var min1 = arr.min();  // 1 

var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:2}];
var min2 = arr2.min(function(t){ return t.Val });   // 1 

Max

Returns the maximum value in a sequence of values.

JavaScript
Array.prototype.max = function (s) {
    s = s || DefaultSelector;
    var l = this.length;
    var max = s(this[0]);
    while (l-- > 0)
        if (s(this[l]) > max) max = s(this[l]);
    return max;
};   

 

Sample:

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
var max1 = arr.max();  // 8 

var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:2}];
var max2 = arr2.max(function(t){ return t.Val });   // 2 

Sum

Computes the sum of a sequence of numeric values.

JavaScript
Array.prototype.sum = function (s) {
    s = s || DefaultSelector;
    var l = this.length;
    var sum = 0;
    while (l-- > 0) sum += s(this[l]);
    return sum;
}; 

 

Sample:

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
var sum1 = arr.sum();  // 36 

var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:2}];
var sum2 = arr2.sum(function(t){ return t.Val });   // 3 

JavaScript LINQ Predicates

Where

Filters a sequence of values based on a predicate.

JavaScript
Array.prototype.where = Array.prototype.filter || function (predicate, context) {
    context = context || window;
    var arr = [];
    var l = this.length;
    for (var i = 0; i < l; i++)
        if (predicate.call(context, this[i], i, this) === true) arr.push(this[i]);
    return arr;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var res = arr.where(function(t){ return t > 2 }) ;  // [3, 4, 5] 

Any

Determines whether any element of a sequence exists or satisfies a condition.

JavaScript
Array.prototype.any = function (predicate, context) {
    context = context || window;
    var f = this.some || function (p, c) {
        var l = this.length;
        if (!p) return l > 0;
        while (l-- > 0)
            if (p.call(c, this[l], l, this) === true) return true;
        return false;
    };
    return f.apply(this, [predicate, context]);
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var res1 = arr.any();  // true
var res2 = arr.any(function(t){ return t > 5 });  // false 

All

Determines whether all elements of a sequence satisfy a condition.

JavaScript
Array.prototype.all = function (predicate, context) {
    context = context || window;
    predicate = predicate || DefaultPredicate;
    var f = this.every || function (p, c) {
        return this.length == this.where(p, c).length;
    };
    return f.apply(this, [predicate, context]);
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var res = arr.all(function(t){ return t < 6 });  // true 

TakeWhile

Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.

Array.prototype.takeWhile = function (predicate) {
    predicate = predicate || DefaultPredicate;
    var l = this.length;
    var arr = [];
    for (var i = 0; i < l && predicate(this[i], i) === true ; i++)
        arr.push(this[i]);

    return arr;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var res = arr.takeWhile(function(t){ return t % 4 != 0 });  // [1, 2, 3] 

SkipWhile
Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.

Array.prototype.skipWhile = function (predicate) {
    predicate = predicate || DefaultPredicate;
    var l = this.length;
    var i = 0;
    for (i = 0; i < l; i++)
        if (predicate(this[i], i) === false) break;

    return this.skip(i);
}; 

 

Sample:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var res = arr.skipWhile(function(t){ return t & 4 != 0 }) ;   // [ 4, 5, 6, 7, 8] 

Contains

Determines whether a sequence contains a specified element.

JavaScript
Array.prototype.contains = function (o, comparer) {
    comparer = comparer || DefaultEqualityComparer;
    var l = this.length;
    while (l-- > 0)
        if (comparer(this[l], o) === true) return true;
    return false;
}; 

 

Sample:

var arr1 = [1, 2, 3, 4, 5]; 
var res1 = arr.contains(2);  // true 

var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:1}]; 
var res2 = arr2.contains({Name:"C", Val:1}, function(a, b){ return a.Val == b.Val }) ;  // true 

JavaScript LINQ Iterations

ForEach

Performs the specified action on each element of the array.

JavaScript
Array.prototype.forEach = Array.prototype.forEach || function (callback, context) {
    context = context || window;
    var l = this.length;
    for (var i = 0; i < l; i++)
        callback.call(context, this[i], i, this);
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
arr.forEach(function(t){ if(t % 2 ==0) console.log(t); });   

DefaultIfEmpty
Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

Array.prototype.defaultIfEmpty = function (val) {
    return this.length == 0 ? [val == null ? null : val] : this;
};  

 

Sample:

var arr = [1, 2, 3, 4, 5];
var res = arr.where(function(t){ return t > 5 }).defaultIfEmpty(5);  // [5]  

History

  • Version 1.5.

License

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