Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Created March 2, 2018 12:39
Show Gist options
  • Select an option

  • Save surferxo3/e7725c5669bac029f1eb460549c03195 to your computer and use it in GitHub Desktop.

Select an option

Save surferxo3/e7725c5669bac029f1eb460549c03195 to your computer and use it in GitHub Desktop.
Counting elements in array of objects using Lodash
// without lodash
let currentGradeId;
let looper = 0;
let tempArray = {};
let finalArray = [];
this.items.forEach((obj, index) => {
currentGradeId = this.items[index].grade_id;
if (tempArray[currentGradeId] === undefined) {
tempArray[currentGradeId] = looper;
finalArray[looper] = {grade: currentGradeId, count: 1}
} else {
finalArray[tempArray[currentGradeId]]['count'] += 1;
}
});
// with lodash
_.map(_.countBy(this.items, 'grade_id'), (value, key) => {
return {grade: key, count: value};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment