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)
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#:
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:
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
:
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.
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 });
SelectMany
Projects each element of a sequence to an array and flattens the resulting sequences into one sequence.
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 });
var res2 = arr.selectMany(function(t){ return t.Values }, function(t, u){ return {Name:t.Name, Val:u}});
Take
Returns a specified number of contiguous elements from the start of a sequence.
Array.prototype.take = function (c) {
return this.slice(0, c);
};
Sample:
var arr = [1, 2, 3, 4, 5];
var res = arr.take(2);
Skip
Bypasses a specified number of elements in a sequence and then returns the remaining elements.
Array.prototype.skip = function (c) {
return this.slice(c);
};
Sample:
var arr = [1, 2, 3, 4, 5];
var res = arr.skip(2);
First
Returns the first element of a sequence.
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();
var t2 = arr.first(function(t){ return t > 2 });
var t3 = arr.first(function(t){ return t > 10 }, 10);
Last
Returns the last element of a sequence.
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();
var t2 = arr.last(function(t){ return t > 2 });
var t3 = arr.last(function(t){ return t > 10 }, 10);
Union
Produces the set union of two sequences by using the default equality comparer.
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);
Intersect
Produces the set intersection of two sequences.
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);
Except
Produces the set difference of two sequences.
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);
Distinct
Returns distinct elements from a sequence by using the default equality comparer to compare values.
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();
var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:1}];
var res2 = arr2.distinct(function(a, b){ return a.Val == b.Val });
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} });
IndexOf
Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.
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);
LastIndexOf
Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.
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);
Remove
Removes the first occurrence of a specific object from the Array.
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);
RemoveAll
Removes all the elements that match the conditions defined by the specified predicate.
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 });
OrderBy
Sorts the elements of a sequence in ascending order according to a key.
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.
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.
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 },
function (u) { return u.Code },
function (t, u) { return { Name: t.Name, Val: t.Val, Code: u.Code } });
var res2 = arr1.innerJoin(arr2,
function (t) { return t.Name },
function (u) { return u.Code },
function (t, u) { return { Name: t.Name, Val: t.Val, Code: u.Code } },
function (a, b) { return a.toUpperCase() == b.toUpperCase() });
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.
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 },
function(u){ return u.Code },
function(t, u){ return {Item:t, Group:u} }) ;
var res2 = arr1.groupJoin(arr2,
function(t){ return t.Name },
function(u){ return u.Code },
function(t, u){ return {Item:t, Group:u} },
function(a, b){ return a.toUpperCase() == b.toUpperCase() });
GroupBy
Groups the elements of a sequence according to a specified key selector function.
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 });
res.forEach(function(t){
console.log("Key: " + t.key, "Length: " + t.length);
});
ToDictionary
Creates an object from an array according to a specified key selector function.
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 });
JavaScript LINQ Aggregations
Aggregate
Applies an accumulator function over a sequence.
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);
Min
Returns the minimum value in a sequence of values.
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();
var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:2}];
var min2 = arr2.min(function(t){ return t.Val });
Max
Returns the maximum value in a sequence of values.
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();
var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:2}];
var max2 = arr2.max(function(t){ return t.Val });
Sum
Computes the sum of a sequence of numeric values.
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();
var arr2 = [{Name:"A", Val:1}, {Name:"B", Val:2}];
var sum2 = arr2.sum(function(t){ return t.Val });
JavaScript LINQ Predicates
Where
Filters a sequence of values based on a predicate.
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 }) ;
Any
Determines whether any element of a sequence exists or satisfies a condition.
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();
var res2 = arr.any(function(t){ return t > 5 });
All
Determines whether all elements of a sequence satisfy a condition.
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 });
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 });
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 }) ;
Contains
Determines whether a sequence contains a specified element.
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);
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 }) ;
JavaScript LINQ Iterations
ForEach
Performs the specified action on each element of the array.
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);
History