I'm trying to categorize an array of questions I've gotten from our application's API, and I've come up with a method that works, but it doesn't feel awesome. Can anyone tell me if there's a better way to do this?
Here's the code I have now. I'm not too worried about making it super optimized, but it shouldn't end up slow.
$scope.patron.categories = questions.map(function(question, i) {
// check if question has a new CategoryId
if(i === 0 || (i > 0 && question.CategoryId !== questions[i-1].CategoryId)) {
// put questions with the same CategoryId together
var catQuestions = questions.filter(function(q) {
return q.CategoryId === question.CategoryId;
});
return {
id: question.CategoryId,
name: question.Category,
collapsed: true,
valid: false,
questions: catQuestions
};
}
}).filter(function(category) {
// because Array.prototype.map doesn't remove these by itself
return category !== undefined;
});