5
var matrix = [
  [11975,  5871, 8916, 2868],
  [ 1951, 10048, 2060, 6171],
  [ 8010, 16145, 8090, 8045],
  [ 1013,   990,  940, 6907]
];

var tr = d3.select("body").append("table").selectAll("tr")
    .data(matrix)
  .enter().append("tr");

var td = tr.selectAll("td")
    .data(function(d) { return d; })
  .enter().append("td")
    .text(function(d) { return d; });

I don't understand what d is representing here. Could someone so kindly walk me through the code?

Reference: https://github.com/mbostock/d3/wiki/Selections#wiki-remove

user3311274
  • 51
  • 2
  • 3
  • [This answer should explain the use of the function in the data-join](http://stackoverflow.com/a/21760476/3128209). – AmeliaBR Feb 14 '14 at 18:06
  • [And this answer should explain the use of functions as parameters more generally](http://stackoverflow.com/a/21421101/3128209), including how it works in the `.text(function)` statement. – AmeliaBR Feb 14 '14 at 18:09

1 Answers1

4

What you have here is a nested selection, i.e. you're making a selection and then a selection based on that. This is also the explanation for the function in the .data() argument -- it is nested below the first, so it can refer to it.

In particular, you're passing in an array of arrays in .data(matrix). D3 will do something for every element of that matrix, i.e. for every array. Here, it is bound to the appended tr elements. So then when you call .data() again, you can refer to the data bound to those elements (the trs). function(d) { return d; } is simply saying that D3 should use the data already bound to it. As that is an array, D3 will do something for every element of it, i.e. append the table cell elements.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204