Skip to content

Instantly share code, notes, and snippets.

@panw
Last active August 29, 2015 14:02
Show Gist options
  • Save panw/d88a0b97f94ddc9bdc96 to your computer and use it in GitHub Desktop.
Save panw/d88a0b97f94ddc9bdc96 to your computer and use it in GitHub Desktop.
Calculate weekly user retention rate using array arithmetic
var weeklyRetention = new Array(); // For storing weekly retntion rate
// Unique user sessions grouped by week
var sessions = [{week: 1, ids: [1, 2, 19, 33]}, {week: 2, ids: [5, 2, 19, 33, 55, 88]},....]
// Loop until second to last element of the array
var i = 0;
while(i < sessions.length-1) {
var usersStartOfPeriod = sessions[i].ids;
var usersEndOfPeriod = sessions[i+1].ids;
// Find users that dropped out for this week
var dropouts = _.difference(usersStartOfPeriod, usersEndOfPeriod);
// Calculate the retention rate for this week
var retention = (usersStartOfPeriod - dropouts)/usersStartOfPeriod
// Store this week's retention rate
weeklyRetention[sessions[i].week] = retention;
i+=1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment