Last active
October 24, 2016 21:00
-
-
Save yehiaa/40c5e62b5ac35731b24a2058f7647802 to your computer and use it in GitHub Desktop.
sort array of objects, get 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
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