Skip to content

Instantly share code, notes, and snippets.

@KarlPurk
Last active December 20, 2015 16:09
Show Gist options
  • Save KarlPurk/6159222 to your computer and use it in GitHub Desktop.
Save KarlPurk/6159222 to your computer and use it in GitHub Desktop.
Reduce an array based on the provided keys, optionally summing specified properties.
/**
* Combine elements of an array based on the provided keys, optionally summing specified properties
* @param data
* @param keys
* @param sum
* @returns array
*/
var arrayCombineSum = function(data,keys,sum) {
/**
* Generate a value from the provides key(s)
* @param object
* @returns {string}
*/
var createKey = function(object, keys) {
var output = [];
keys.forEach(function(key) {
if (object[key] === undefined) {
return;
}
output.push(object[key]);
})
return output.join('');
}
// Reduce the array based on user specified key(s)
return data.reduce(function(output, object) {
// Generate a primary key for this object based on the user provided keys
var pk = createKey(object, keys);
// Add the element to the output data if it doesn't already exist
if (!(pk in output)) {
output.data.push(output[pk] = object);
}
else {
// Sum requested values
sum.forEach(function(key) {
output[pk][key] += object[key];
});
}
return output;
}, {data:[]}).data;
};
data = [];
sites = ["Site A", "Site B"];
locations = ["Location A", "Location B", "Location C"];
for (var month = 7; month <= 8; month++) {
for (var day = 1; day <= 31; day++) {
sites.forEach(function(site) {
locations.forEach(function(location) {
data.push({
site: site,
location: location,
day: day,
month: month,
date: day + '/' + month + '/2013',
expected: 25 + Math.ceil(Math.random() * 10),
actual: 15 + Math.ceil(Math.random() * 10)
});
})
});
}
}
// Monthly, by site
console.log(arrayCombineSum(data, ['site', 'month'], ['expected', 'actual']));
// Monthly, by site & location
console.log(arrayCombineSum(data, ['site', 'location', 'month'], ['expected', 'actual']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment