B T
B T

Reputation: 161

Getting array length with d3

I'm having trouble returning an array length. I have an array as follows:

var colorsquares = [
                [3.3, 28, -1.5, 13, 857, 3, 5, 6, 7, 5, ["#b2dbbb","#d2e6c1"]],
                [1.3, 18, -1.5, 13, 857, 3, 5, 6, 7, 5, ["#c2dccc","#d2fdc1"]]
                ];

and I'm using the last values to color divs

d3.select("#colorBox")
          .selectAll("div")
          .data(d[10])
          .enter()
          .append("div")
          .style("background-color", function(d) { 
               return d; 
           })
           .style("width", function(d) { 
               return (d.length + 1) + "px"; 
           })
           ;

The colors are coming out right but I'm not getting what I want for the width. Instead of 2, I'm getting 8.

Upvotes: 1

Views: 12145

Answers (1)

Shai
Shai

Reputation: 7307

Within a D3 styling function:

.style("width", function(d) { 
    return (d.length + 1) + "px"; 
})

, that first parameter (which you have called d) represents the individual array element, for example "#b2dbbb" or "#d2e6c1". D3 passes the first array element ("#b2dbbb") to the first div, second ("#d2e6c1") to the second div, and so on. So when you ask for d.length + 1, you are asking for the length of the string "#b2dbbb" + 1 which is, indeed, 8.

I think your confusion comes because you have used the name d for two separate purposes, and one is hiding the other. You use it as the parameter within the function, but also as a reference to colorsquares[0] or colorsquares[1] (are these in some kind of loop or something? I can't be more specific because you haven't posted all your code.)

For example, change the OUTER d (the one you are referring to when you say .data(d[10])) to be called dd (or a better name, ideally). Then, in the background color function you are right to say

return d

But in the width function, I think you are looking for

return (dd[10].length + 1) + "px";

Upvotes: 1

Related Questions