Skip to content

Instantly share code, notes, and snippets.

@wesscoby
Created April 13, 2019 19:31
Show Gist options
  • Save wesscoby/2d82161ca0b03f9f27dc0561ae026d5c to your computer and use it in GitHub Desktop.
Save wesscoby/2d82161ca0b03f9f27dc0561ae026d5c to your computer and use it in GitHub Desktop.
Categorize data(an array of objects) based on a specified category (a property in the data)
/*
* Categorize data based on a specified category (a property in the data)
* @data an array of objects
* @category the criteria for categorizing the @data. @category must be a property in @data
*/
module.exports = (data, category) => {
// Get the category list with which to categorize the data
// getCategoryList is assigned to an iife
let getCategoryList = (() => {
let categoryList = [];
data.forEach(value => {
if (!categoryList.includes(value[category])) {
categoryList.push(value[category]);
}
});
return categoryList;
})();
// Sort the data according to the category list
let newObject = {};
getCategoryList
.forEach(categoryItem => newObject[categoryItem] = data
.filter(Obj => Obj[category] === categoryItem)
.map(entry => {
delete entry[category];
return entry;
}));
// Return categorized data and category list
return {
categoryList: getCategoryList,
data: newObject
};
};
@wesscoby
Copy link
Author

Example:
// Save to file and import or require it...
import categorizeData from '/path/to/categorizeData.js'

const bills = [
{date: '2018-01-20', amount: '220', category: 'Electricity'},
{date: '2018-01-20', amount: '20', category: 'Gas'},
{date: '2018-02-20', amount: '120', category: 'Electricity'}
];

let categorizedBills = categorizeData(bills, 'category')

// categorizedBills.categoryList returns [ 'Electricity', 'Gas' ]

/*
categorizedBills.data returns:
{
Electricity: [ { date: '2018-01-20', amount: '220' }, { date: '2018-02-20', amount: '120' } ],
Gas: [ { date: '2018-01-20', amount: '20' } ]
}

*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment