Created
September 14, 2013 18:09
-
-
Save mcsheffrey/6564211 to your computer and use it in GitHub Desktop.
Function that returns array of top 3 values of an object
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 = { | |
'a': 5, | |
'b': 10, | |
'c': 4, | |
'd': 11 | |
}, | |
tempArr = [], | |
returnArr = []; | |
function sortObject(items) { | |
for (var key in items) { | |
if (items.hasOwnProperty(key)) { // filter | |
tempArr.push({name: key, value: items[key]}); | |
} | |
} | |
tempArr.sort(function(a, b) { | |
if (a.value < b.value) | |
return 1; | |
if (a.value > b.value) | |
return -1; | |
return 0; | |
}); | |
for (var i = 0; i < 3; i++) { | |
returnArr.push(tempArr[i].name); | |
}; | |
return returnArr; | |
} | |
sortObject(items); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment