Created
March 19, 2017 06:47
-
-
Save Deminem/d781c47359d767b6a2bc1f882b671d20 to your computer and use it in GitHub Desktop.
A simple javascript to ordered the collection through given property and also calculate the average
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
(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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: