Created
April 13, 2019 19:31
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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' } ]
}
*/