Work with Data in D3 understanding data and enter

Work with Data in D3 understanding data and enter
0

#1

This code snippet is supposed to be printing New Title 9 times but it is printing it only 7 times. Please help me understand why is that happening

Your code so far


<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14,9];
    
    // Add your code below this line
const new_t = d3.select("body")
                .selectAll("h2")
                .data("dataset")
                .enter()
                .append("h2")
                .text("New Title")
    
    
    // Add your code above this line
  </script>
</body>

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/data-visualization/data-visualization-with-d3/work-with-data-in-d3


#2

because in data you have string "dataset" which have length 7 instead of variable dataset


#3

@lubodrinka Thanks . I missed looking at that.


#4

Hi, In this example, we selectAll h2 tags and then we append h2 on iteration. Looks something redundant and hard to understand. Any help?


#5

It’s the way d3 works ^^
I don’t remember the correct terminology, but basically selectAll returns you all the actual h2. Let’s call them ‘containers’ and say you already have 3 in your graph ( 3 h2).
Then you use the data method, which select the data to put into the containers. Let’s say you have 5.

Now you have 3 containers and 5 data. What’s happen? You need 2 more containers!
That’s what append is made for: you choose the container type you want to use to accomodate the remaining data ( again h2, or whatever you want^^).

In the above example, the selectAll returned 0 ( it’s usual as far as i could see ) so you have 9 ‘emply slot’ to fill - with what? - with the argument of append!
The problem was that passing the string and not the array ( which both have the length property) the ‘empty slots’ were 7 ( "dataset".length ) not 9 (
[12, 31, 22, 17, 25, 18, 29, 14,9].length)