Created
September 9, 2009 21:10
-
-
Save kocolosk/184083 to your computer and use it in GitHub Desktop.
reduce function to return a sorted array of the top 50 values
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
function(doc) { | |
emit(doc.parent_id, doc.visits); | |
} | |
function (keys, values, rereduce) { | |
var result = []; | |
var unique_keys = []; | |
function add_to_result(parent_id, visits) { | |
var index = unique_keys.indexOf(parent_id); | |
if (index == -1) { | |
unique_keys.push(parent_id); | |
result.push({"parent_id":parent_id, "visits":visits}); | |
} else { | |
result[index].visits += visits; | |
} | |
} | |
function sort_result(a,b) { | |
if (a.visits < b.visits) return 1; | |
if (a.visits > b.visits) return -1; | |
return 0; | |
} | |
if (!rereduce) { | |
for (var i in keys) { | |
add_to_result(keys[i][0], values[i]); | |
} | |
} | |
else { | |
for each (var reduction in values) { | |
for each (var item in reduction) { | |
add_to_result(item.parent_id, item.visits); | |
} | |
} | |
} | |
return result.sort(sort_result).slice(0,50); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment