Enhancing the capabilities of arrays by extending the Array prototype allows for efficient manipulation and operations in a functional programming approach. The snippet below showcases how this can be achieved:
arr.flatten().select('code').forEach(function (code) { console.log('code: ' + code) })
To implement these functions in your own code, you will need to include them as shown below:
Array.prototype.select = function (prop) {
var arr = this;
var ret = [];
for (var i = 0; i < arr.length; i++) {
ret.push(arr[i][prop]);
}
return ret;
}
Array.prototype.flatten = function () {
var arr = this.valueOf();
var ret = [];
arr.forEach(function (item) {
if (Array.isArray(item)) {
item.forEach(function (itm) {
ret.push(itm);
});
}
else {
ret.push(item);
}
});
return ret;
}
If you find this useful, you may want to explore additional array manipulation functions available at https://github.com/mykeels/ArraysJS. There is a variety of other helpful functions waiting to be discovered.