Grouping / counting in javascript using underscore.js
I am new to javascript (and for) and I am facing a problem that I cannot solve. I am trying to create a simple pie chart that shows the number of projects for each technology value in my data. This is the data I'm working with:
- [Project1, Java]
- [Project2, Excel]
- [Project3, SAS]
- [Project4, Java]
The aspect ratio in the above example would be 2: 1: 1.
The first part of my code loads the data and pushes it into the "techArray" which contains [project, tech]. This part works fine - I tested it in a simplified version of the code.
Then I want to group the "techArray" and count the instances of each technology. For this I use the Underscore library as follows:
var chartData = [];
var techData = _.groupBy(techArray, 'tech');
_.each(techData, function(row) {
var techCount = row.length;
chartData = push( {
name: row[0].tech,
y: techCount
});
});
The script then displays the chartData array using tall charts. Again, I have verified that this section works using a simplified (non-group) version.
There must be a problem with the grouping / counting step described above because I can't see the way out, but I just can't find where. I base my solution on the following example: Working example .
If anyone can spot an error in what I have written, or suggest another way to group an array, I would be very grateful. It seems that this should be an easier task than it would be.
source to share
countBy can be used instead of groupBy:
var techArray = [
{ project: 'Project1', tech: 'Java'},
{ project: 'Project2', tech: 'Excel'},
{ project: 'Project3', tech: 'SAS'},
{ project: 'Project4', tech: 'Java'},
];
var counts = _.countBy(techArray,'tech');
This will return an object with tech properties and their value as count:
{ Java: 2, Excel: 1, SAS: 1 }
To get the data in the form for tall cards, use a card instead of each:
var data = _.map(counts, function(value, key){
return {
name: key,
y: value
};
});
source to share
This should work
var techArray = [['Project1','Java'], ['Project2', 'excel'], ['Project3', 'Java']];
var chartData = [];
var techData = _.groupBy(techArray, function(item) {
return item[1];
});
_.each(techData, function(value, key) {
var techCount = value.length;
chartData.push({
name: key,
y: techCount
});
});
_.groupBy
you either need to get the property name or a function that returns a grouped value. There is no property tech
for the array, so you cannot group it. But since ours techArray
is an array of tuples, we can pass a function _.groupBy
that returns the value we want for groupBy, namely the second element in each tuple.
chartData
now looks like this:
[{
name: 'Java',
y: 2
}, {
name: 'excel',
y: 1
}]
source to share