Skip to content

Instantly share code, notes, and snippets.

@Deminem
Created March 19, 2017 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deminem/d781c47359d767b6a2bc1f882b671d20 to your computer and use it in GitHub Desktop.
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
(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);
})();
@Deminem
Copy link
Author

Deminem commented Mar 19, 2017

Result:

SortBy Name:  [John 32],[Martin 18],[Steve 26]
SortBy Age:  [Martin 18],[Steve 26],[John 32]
Average Ranking:  76

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment