JavaScript Array LINQ Equivalents
Following are some of JavaScript Array equivalent methods of LINQ.
LINQ | JavaScript Array |
---|---|
Filter | |
Where | Array.prototype.filter |
Order | |
OrderBy | Array.prototype.sort |
OrderByDescending | Array.prototype.sort |
Reverse | Array.prototype.reverse |
Project | |
Select | Array.prototype.map |
Aggregate | |
Count | Array.length |
Aggregate | Array.prototype.reduce |
Find | |
Contains | Array.prototype.some |
Any | Array.prototype.some |
All | Array.prototype.every |
However, LINQ query is actually Deferred Execution, which is the exact idea of JavaScript ES6 Iterator and Generator. Here is how I implement Where and Select with JavaScript yield.
class LinqArray {
constructor(iterator) {
this.iterator = iterator;
}
static from(array) {
return new LinqArray(function () {
return array;
});
}
where(predicate) {
const { iterator } = this;
return new LinqArray(function* () {
for (const item of iterator()) {
if (predicate(item)) {
yield item;
}
}
});
};
select(project) {
const { iterator } = this;
return new LinqArray(function* () {
for (const item of iterator()) {
yield project(item);
}
});
};
}
The hardest part of the above codes is how to make the iterators chainable. Now, you can use it as below:
const iter = LinqArray
.from([3,4,6,7])
.where(n => n % 2 === 0)
.select(n => n * 2)
.iterator();
for (const n of iter) {
console.log(n);
}