Reputation:
I have a JSON file which I am using for visualization using d3.js. I want to get the count of total rows for a particular code. I am using the following for doing so:
data.keys(d.code).length
But its not working. How can I solve this? I have found one idea but it is not showing correct values. Whats the wrong with it?
Object.keys(d.code).length
I have a JSON file with following sample data
[
{"name":"a","code":20},
{"name":"b","code":20},
{"name":"c","code":20},
{"name":"d","code":21}
]
My target is to get the count of data with same code. For example for code 20 I should get 3 as output.
Upvotes: 0
Views: 1530
Reputation: 21578
You might as well use d3.nest()
to group your data based on code
and have it return the number of entries per group:
var json = [
{"name":"a","code":20},
{"name":"b","code":20},
{"name":"c","code":20},
{"name":"d","code":21}
];
var nest = d3.nest()
.key(function(d) { return d.code; })
.rollup(function(values) { return values.length; })
.entries(json);
Upvotes: 1
Reputation: 5375
var count = 0;
var length = data.length;
for (var x = 0; x < length; x++)
{
if (data[x].code == 20)
count++;
}
console.log('Final count: ' + count);
Probably something like that.
If you want a function you could use this:
var getCount = function(data, val)
{
var count = 0;
var length = data.length;
for (var x = 0; x < length; x++)
{
if (data[x].code == val)
count++;
}
return count;
}
Then call it like this:
var count = getCount(data, 20); // should return 3
Upvotes: 0
Reputation: 14053
You don't need D3.js for this. Simple JavaScript should do it. Something like:
total = data.reduce(function(count, entry) {
return count + (entry.code === 20 ? 1 : 0);
}, 0);
Obviously, you can convert it to a function to handle arbitrary values other than 20.
Upvotes: 0