Skip to content

Instantly share code, notes, and snippets.

@mcsheffrey
Created September 14, 2013 18:09
Show Gist options
  • Save mcsheffrey/6564211 to your computer and use it in GitHub Desktop.
Save mcsheffrey/6564211 to your computer and use it in GitHub Desktop.
Function that returns array of top 3 values of an object
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