Skip to content

Instantly share code, notes, and snippets.

@mjpitz
Last active June 29, 2018 15:51
Show Gist options
  • Save mjpitz/7aed34ddc4bbc9b45999 to your computer and use it in GitHub Desktop.
Save mjpitz/7aed34ddc4bbc9b45999 to your computer and use it in GitHub Desktop.
Useful data analysis methods for NodeJS.
/**
* @fileoverview Useful data operations for manipulating large sets of data.
*
* I initially wrote this utility for handling the idea-frameworks
* documentation generator where I would group and regroup data into more
* manageable chunks.
*/
var util = require('util');
/**
* Helper function to group the data by a single term.
*
* @param {Array|Object} data The data that we want to group.
* @param {string} term The term we are currently grouping by.
* @return {Object} The grouped object.
* @private
*/
var groupBy_ = function(data, term) {
var target = {};
if (util.isArray(data)) {
data.forEach(function(doc) {
if (!target[doc[term]]) target[doc[term]] = [];
target[doc[term]].push(doc);
});
} else {
for (var key in data) {
target[key] = groupBy_(data[key], term);
}
}
return target;
};
/**
* Group data by many terms.
*
* @param {Array|Object} data The data we want to group.
* @param {Array.<string>} terms The terms we are grouping on.
* @return {Object} The newly grouped data by all the provided terms.
*/
exports.groupBy = function(data, terms) {
var groupedData = data;
terms.forEach(function(term) {
groupedData = groupBy_(groupedData, term);
});
return groupedData;
};
/**
* Flattens a grouped object into a single array.
*
* @param {Array|Object} data The data that we are flattening.
* @return {Array} The flattened array of data.
*/
exports.regroup = function(data) {
if (util.isArray(data)) {
return data;
} else {
var array = [];
for (var key in data) {
array = array.concat(this.regroup(data[key]));
}
return array;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment