简体   繁体   中英

Javascript D3 How to access and manipulate dataset from CSV

I am struggling with D3. I have a dataset that I am pulling into D3, and populating a bar chart. The problem is there are too many bars! I want to only display the top 10 values.

My csv has two values, the key (column header) is "Name" and the value is "NumberOfTickets". I want to show only 10 names that have the most tickets. I assume i need to sort and splice my dataset, but I have tried everything and cant get it to work. It seems most tutorials are geared towards simple arrays and not a dataset that comes from a CSV with key value pairs. Any help would be appreciated. Here is my dataset portion of the D3 code. I assume this is where I need to manipulate the dataset:

  var report = data.forEach(function(d){                    
                d.Name= d.Name;
                d.NumberOfTickets= +d.NumberOfTickets;                          
            });

Try this:

var report = data.sort(function(a, b) {
                return d3.descending(+a.NumberOfTickets, +b.NumberOfTickets);
            }).slice( 0, 10);

If you want the names that get less tickets, just change for "ascending". If you want to change your slice, remember that the start number is inclusive, but the ending number is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM