Jeffrey van Binsbergen.nl

JavaScript Array extensions

For my Japanese learn site I needed a way to quickly filter on an array of objects in JavaScript. I really like LINQ in C# and I missed it in JavaScript. So I decided to make it myself, which barely took 5 minutes but saved me probably hours and a lot of repetitive loops.

Array.prototype.Where = function (func) {
var items = [];
for (var i = 0; i < this.length; i++) {
if (func(this[i]))
items.push(this[i]);
}
return items;
};

Array.prototype.First = function (func) {
for (var i = 0; i < this.length; i++) {
if (func(this[i]))
return this[i];
}
};

Array.prototype.Take = function (count) {
var items = [];
for (var i = 0; i < this.length && i < count; i++) {
items.push(this[i]);
}
return items;
};

Array.prototype.Skip = function (count) {
var items = [];
for (var i = count; i < this.length; i++) {
items.push(this[i]);
}
return items;
};

Array.prototype.OrderBy = function (func) {
return this.sort(function (a, b) {
return func(a) - func(b);
});
};

Array.prototype.Select = function (func) {
var items = [];
for (var i = 0; i < this.length; i++)
items.push(func(this[i]));
return items;
};

Array.prototype.Max = function (func) {
var highest = null;
for (var i = 0; i < this.length; i++) {
var value = func(this[i]);
if (highest == null || value > highest)
highest = value;
}
return highest;
};

Array.prototype.Unique = function (func) {
var items = [];
var uniqueKeys = [];
for (var i = 0; i < this.length; i++) {
var key = func(this[i]);
if (uniqueKeys.indexOf(key) < 0) {
items.push(this[i]);
uniqueKeys.push(key);
}
}
return items;
};

Array.prototype.Randomize = function () {
var items = this.slice();
var currentIndex = items.length, temporaryValue, randomIndex;

while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

temporaryValue = items[currentIndex];
items[currentIndex] = items[randomIndex];
items[randomIndex] = temporaryValue;
}
return array;
};

A few examples of cool stuff you can do by using this code:

var colors = [
{ name: "Blue", votes: 2 },
{ name: "Green", votes: 9 },
{ name: "Red", votes: 1 }
];

var color = colors.First(function (a) { return a.votes > 5 });
alert(color.name); // Green

var filteredColors = colors.Where(function (a) { return a.votes < 5 });
alert(filteredColors.length); // 2

var colorsInUppercase = colors.Select(function (a) {
return { name: a.name.toUpperCase(), votes: a.votes }
}).OrderBy(function(a) {
return a.votes;
});
alert(colorsInUppercase[0].name); // RED

Of course, after making those few functions and being all happy about it... I saw that are multiple existing projects which do just the same thing. Oh well, I like to make stuff myself anyway.

Show all articles