Created
March 19, 2017 06:47
Revisions
-
Deminem created this gist
Mar 19, 2017 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,58 @@ (function() { 'use strict'; // create a person function Person(name, ranking) { this.name = name; this.ranking = ranking; this.toString = function() { return '[' + this.name + ' ' + this.ranking + ']'; } } // sort by given property Array.prototype.sortBy = function(prop) { return this.slice(0).sort(function(o1, o2) { if (o1[prop] > o2[prop]) { return 1; } else if (o1[prop] < o2[prop]) { return -1; } return 0; }); }; // calculate the average for given property i.e number Array.prototype.average = function(prop) { var average = 0; this.forEach(function(obj) { if (typeof obj[prop] === 'number') { average += obj[prop]; } }); return average; }; // print the array Array.prototype.print = function() { return this.slice(0).toString(); }; // create the person object array var personItems = [ new Person('John', 32), new Person('Martin', 18), new Person('Steve', 26) ]; // sort array w.r.t age and name var sortByName = personItems.sortBy('name'); var sortByAge = personItems.sortBy('ranking'); var average = personItems.average('ranking'); // print the output on console console.log('SortBy Name: ', sortByName.print()); console.log('SortBy Age: ', sortByAge.print()); console.log('Average Ranking: ', average); })();