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
};
};