Skip to content

Instantly share code, notes, and snippets.

@yehiaa
Last active October 24, 2016 21:00
Show Gist options
  • Save yehiaa/40c5e62b5ac35731b24a2058f7647802 to your computer and use it in GitHub Desktop.
Save yehiaa/40c5e62b5ac35731b24a2058f7647802 to your computer and use it in GitHub Desktop.
sort array of objects, get average
var items = [{name:'a', rank:3},{name:'b', rank:2},{name:'d', rank:1},{name:'c', rank:4}];
function getAverage(itemsArray){
var total = 0 ;
itemsArray.map(function (item){
total += item.rank ;
} );
return total / itemsArray.length ;
}
function sortItems(itemsArray){
// the items is passed by reference
itemsArray.sort(function (itemA, itemB){
if (itemA.name < itemB.name) {
return -1;
}
if (itemA.name > itemB.name) {
return 1;
}
return 0;
} );
}
var avgResult = getAverage(items);
sortItems(items);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment