ACPrice
ACPrice

Reputation: 677

Counting data items in d3.js

I have some data. It looks like this (but with several hundred objects in the array rather than three):

var data = [
{
    id: "1",
    name: "Name1",
    color: "Color1"
},
{
    id: "2",
    name: "Name2",
    color: "Color2"
},
{
    id: "1",
    name: "Name3",
    color: "Color3"
}

What I want to do is draw a rectangle which has a height that corresponds to the number of items in the data which have a certain id value. So, for example, if there were 300 items in the data array with an id of "1", then the rectangle would be 300 pixels tall.

Obviously I could loop through the array and count them up, but I want to know if there's an easier/shorter way in d3.js.

What I have in mind might look like this:

svg.selectAll('rect').data(data).enter()
    .append('rect')
        .attr('x', 800)
        .attr('y', 800)
        .attr('height', //SOME CODE HERE)
        .attr('width', 5)
        .attr('fill', 'red')

Upvotes: 2

Views: 11851

Answers (1)

jhyap
jhyap

Reputation: 3837

You would need to do two things:

1) group your Id to get the count

2) set the count value as height attribute for d3 rect

The below code will group your id by indexing it. The length of the groupId would be the count for common id inside your data:

var groupId = [];
var maxId = 0;
for (var i = 0; i < data.length; i++){
    var item = data[i];

    if (!groupId[item.id]){
        groupId[item.id] = [];
    }

    groupId[item.id].push({name: item.name, color:item.color});

    if (maxId < item.id){
        maxId = item.id;
    }
}

Then for your d3

//Make an SVG Container
var svgContainer = d3.select("body").append("svg").attr("width", 200).attr("height", 200);

for (var i = 1; i <= maxId; i++){

    console.log("length of groupId is " + groupId[i].length);
    console.log("Id is " + i);
    for (var j = 0; j < groupId[i].length; j++){
         console.log("name is " + groupId[i][j].name + " color is " + groupId[i][j].color);
    }
    console.log("===========================");
 //Draw the Rectangle
 var rectangle = svgContainer
                 .append("rect")
                 .attr("x", i*10)
                 .attr("y", i)
                 .attr("width", 5)
                 .attr("height", groupId[i].length);
}

Check the console log, will help you understand the array better.

Demo JSFiddle

Upvotes: 2

Related Questions