I often found myself wanting to do certain operations for all the items in an array and I wished that JavaScript had something like C#'s LINQ. So, to that end, I whipped up some extensions of the Array prototype:
var data = [1, 2, 3];
Array.prototype.sum = function () {
var total = 0;
for (var i = 0; i < this.length; i++) {
total += this[i];
}
return total;
};
Array.prototype.first = function () {
return this[0];
};
Array.prototype.last = function () {
return this[this.length - 1];
};
Array.prototype.average = function () {
return this.sum() / this.length;
};
Array.prototype.range = function () {
var self = this.sort();
return {
min: self[0],
max: self[this.length-1]
}
};
console.log(data.sum()) <-- 6
This makes working with arrays much easier if you need to do some mathematical processing on them. Are there any words of advice against using a pattern like this? I suppose I should probably make my own type that inherits from Array's prototype, but other than that, if these arrays will only have numbers in them is this an OK idea?
To extend an existing array in JavaScript, use the Array. concat() method.
For instance, Array extends Object . Normally, when one class extends another, both static and non-static methods are inherited. That was thoroughly explained in the article Static properties and methods.
Creating a Nested Array: This one is just equating the variable to the array. Second one is using the array method new Array() . And the last one is using the Array() which is similar to the new Array() . Note that all these methods yield the same result.
Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
Generally speaking you should avoid extending base objects because it may clash with other extensions of that object. Ideally extending Array and then modifying THAT is the safest way to do things as it is guaranteed to not clash with other developers who might try to do the same thing (even though they shouldn't).
Basically, avoid extending base objects when possible because it can get you into trouble for very little real benefit compared to extending the array object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With