D3 and JavaScript: how to ingest a CSV file and render filtered output to HTML?

Viewed 19

I have data in CSV file named test.csv that I'd like to filter, then render to an HTML element.

Here is the data:

shape,color,distance
circle,blue,4
square,red,2
circle,blue,7
circle,green,9
triangle,blue,1
square,green,3
octagon,blue,4

I'd like to filter by color === 'blue', then output the length of the result set to an HTML element.

Here is my attempt:

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>D3 Page Template</title>
            <script type="text/javascript" src="d3.js"></script>
        </head>
        
        <body>


            <script type="text/javascript">
                // JavaScript code here

            d3.csv('test.csv', d3.autoType).then(function(data) {
                   console.log(data);
                   let filteredData = data.filter(function (d) {
                  return d.color === 'blue'
                  })
                  console.log(filteredData)
                  console.log(filteredData.length)
             });

            
            d3.select("body")
              .data(filteredData)
              .enter()
              .append("p")
              .text('Records returned:', filteredData.length)


           </script>
        </body>
    </html>

I can see the filteredData object in console.log(filteredData), but I'm unable to render its length (in this case, 4) to the screen.

How do I render 'Records returned: 4' to HTML?

Thanks in advance!

0 Answers
Related