Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 Data Binding - When to put brackets around data

I'm looking at multiple D3 code examples similar to this:

var data = [1,2,3...];
var blah = d3.selectAll("#blah").data([data]).enter()...;

But sometimes I'll see it as this:

var data = [1,2,3...];
var blah = d3.selectAll("#blah").data(data).enter()...

All the code I've written has been in the second form and I've never had any issue, but I copied a code example online that was in the first form and it did not work when I removed the [].

Can someone explain why it's necessary here and when we should put brackets around what's already an array object?

Thanks.

like image 415
zachvac Avatar asked Dec 24 '16 05:12

zachvac


1 Answers

In d3. the data() method accepts three things:

  • A function
  • An array
  • Nothing (when it acts as a getter).

That being said, this is the issue:

In most situations, you can simply pass ["foo", "bar", "baz"] as the data. So, if you have:

var data = ["foo", "bar", "baz"];

You can simply write:

.data(data)

However, in some situations, as when an element inherits the data of a parent group, you have to wrap it in an extra pair of brackets (check this recent answer I wrote). We do that because the child element gets its data as a function, where the parent's datum is passed.

Check this:

var data = ["foo", "bar", "baz"];

var body = d3.select("body");

var divs = body.selectAll(".divs")
	.data(data)
	.enter()
	.append("div");
	
var par = divs.selectAll("p")
	.data(d => d)
	.enter()
	.append("p")
	.text(d => d);
<script src="https://d3js.org/d3.v4.min.js"></script>

Now, the same code, with an extra pair of brackets:

var data = ["foo", "bar", "baz"];

var body = d3.select("body");

var divs = body.selectAll(".divs")
	.data([data])
	.enter()
	.append("div");
	
var par = divs.selectAll("p")
	.data(d => d)
	.enter()
	.append("p")
	.text(d => d);
<script src="https://d3js.org/d3.v4.min.js"></script>

In the first snippet, 3 divs are created. For each one, a string datum is passed to the paragraphs (d3 will turn each string, such as "foo", in an array such as ["f", "o", "o"], and you'll get 3 paragraphs for each div).

In the second snippet just one div is created (since our array's length is just 1), and the entire inner array (["foo", "bar", "baz"]) is passed to the paragraphs.

like image 172
Gerardo Furtado Avatar answered Oct 18 '22 07:10

Gerardo Furtado