How would you add your own method to the Array object so the following code would work?

Technology CommunityCategory: JavaScriptHow would you add your own method to the Array object so the following code would work?
VietMX Staff asked 3 years ago
Problem
var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg);

JavaScript is not class based, but it is a prototype-based language. This means that each object is linked to another object, its prototype, and it inherits its methods. You can follow the prototype chain for each object up until you reach the null object which has no prototype. We need to add a method to the global Array object, and we will do this by modifying the Array prototype.

Array.prototype.average = function() {
  // calculate sum
  var sum = this.reduce(function(prev, cur) { return prev + cur; });
  // return sum divided by number of elements
  return sum / this.length;
}

var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg); // => 3