Created
October 28, 2020 13:43
-
-
Save torrobinson/12d869a063e10c9d4c9f06116f2cbc0f to your computer and use it in GitHub Desktop.
LINQ-esque javascript array estentions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.where = function (condition) { | |
return this.filter(condition); | |
}; | |
Array.prototype.select = function (attributes) { | |
return this.map(attributes); | |
}; | |
Array.prototype.sum = function () { | |
return this.reduce((a, b) => a + b, 0); | |
}; | |
Array.prototype.average = function () { | |
return this.sum() / this.length; | |
}; | |
Array.prototype.any = function (condition) { | |
if (condition === undefined) { | |
return this.length > 0; | |
} | |
return this.filter(condition).length > 0; | |
}; | |
Array.prototype.first = function() { | |
return this[0]; | |
}; | |
Array.prototype.not = function(object) { | |
return this.filter((thing) => { return thing != object }); | |
}; | |
Array.prototype.take = function(count) { | |
return this.slice(0, count); | |
}; | |
Array.prototype.unique = function() { | |
return this.sort().filter(function(value, index, array) { | |
return (index === 0) || (value !== array[index - 1]); | |
}); | |
}; | |
Array.prototype.skip = function(count) { | |
return this.slice(count, this.length); | |
}; | |
Array.prototype.copy = function () { | |
return this.slice(0); | |
} | |
Array.prototype.max = function () { | |
return Math.max.apply(Math, this); | |
} | |
Array.prototype.min = function () { | |
return Math.min.apply(Math, this); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment