disp_name
disp_name

Reputation: 1488

D3: How to add an extra column to the table which is not in csv columns

Scenario: I am reading data about countries from a .csv file. I am able to sort this data based on one column and also to filter out top 30 countries based on the score.

I am taking column names from the .csv file headers. Additionally, I want to add "Rank" column which is not in .csv file.

How can I do that?

Below is my code for generating table:

var table = d3.select("body").append("table")
                    .attr("style", "margin-left: 50px")
                    .attr("class", "table table-hover table-sm")
                    .attr("id", "tab_id"),
                thead = table.append("thead")
                    .attr("class","tab-head"),
                tbody = table.append("tbody");

                // Append the header row
                thead.append("tr")
                    .selectAll("th")
                    .data(columns)
                    .enter()
                    .append("th")
                    .text(function(column) { return column; });

                // Create a row for each object in the data
                var rows = tbody.selectAll("tr")
                    .data(top_nations)
                    .enter()
                    .append("tr");

                // create a cell in each row for each column
                var cells = rows.selectAll("td")
                    .data(function(row) {
                        return columns.map(function(column) {
                            return {
                                column: column, value: row[column]
                            };
                        });
                    })
                    .enter()
                    .append("td")
                    .attr("style", "font-family: Courier") // sets the font style
                    .html(function(d) { return d.value; });

Can I add an additional column with Ranking 1 to 30 here? Or Do I need to do something when I am reading data and doing sorting and getting top 30 records stuff?

Would appreciate any help.

Upvotes: 2

Views: 1232

Answers (1)

CMartins
CMartins

Reputation: 3293

Try

$('#table').find('tr').each(function(){
        $(this).find('td').eq(x).after('<td>&nbsp;</td>');
   });

x will be the number of the column you want to create after

Upvotes: 2

Related Questions