Search code examples
javascriptpythoncherrypy

How can I select columns from a table generated in JS from a csv file, to do a further analysis with only the selected columns?


For this project I am using python and JS. The framework I'm using is cherrypy and for html I'm using yattag. (I'm a beginner btw) I have generated a table from a csv file with the following JS code example I found:

let picker = document.getElementById("demoPick"), 
table = document.getElementById("demoTable"); 

picker.onchange = () => { 
    table.innerHTML = "";


    let reader = new FileReader(); 
    
    reader.addEventListener("loadend", ()=> {
    
        let csv = reader.result.split("\r\n").slice(0,20);
        for (let row of csv) { 
            let tr = table.insertRow(); 
            for (let col of row.split(",")){ 
                let td = tr.insertCell(); 
                td.innerHTML = col; 
            }
        }
    });
    reader.readAsText(picker.files[0]);

The next step for my project is to select columns from the generated table (with checkboxes or any other way), to then use the data of these columns for further steps of the project.. Any ideas on how to do this?


Solution

  • const picker = document.querySelector('#demoPick');
    const table = document.querySelector('#demoTable');
    const output1 = document.querySelector('#output1');
    const output2 = document.querySelector('#output2');
    
    const isColSelectedByNum = {};
    const itemsByColNum = [];
    
    picker.onchange = () => {
        const reader = new FileReader();
    
        reader.addEventListener('loadend', () => {
            const lines = reader.result.split('\n').slice(0, 20);
            const colNumbers = lines[0].split(',').map((_, i) => i);
    
            //fill itemsByColNum
            const itemByColByRow = lines.map(line => line.split(','));
            for (let colNum of colNumbers) {
                for (let rowNum = 0; rowNum < lines.length; rowNum++) {
                    const item = itemByColByRow[rowNum][colNum];
                    itemsByColNum[colNum] = itemsByColNum[colNum] || [];
                    itemsByColNum[colNum].push(item);
                }
            }
    
            //render the table
            let html = '';
            for (let colNum of colNumbers) {
                html += '<th>';
                html += 'col' + colNum;
                html += '</th>';
            }
            for (let line of lines) {
                const rowItems = line.split(',');
                html += '<tr>';
                for (let colNum = 0; colNum < rowItems.length; colNum++) {
                    const item = rowItems[colNum];
                    html += `<td>`;
                    html += item;
                    html += '</td>';
                }
                html += '</tr>';
            }
            table.innerHTML = html;
    
            //handle clicking on table column headers by toggling selected
            const columnHeaders = document.querySelectorAll('th');
            const allTrs = document.querySelectorAll('#demoTable tr');
            for (let colNum = 0; colNum < columnHeaders.length; colNum++) {
                const columnHeader = columnHeaders[colNum];
                columnHeader.addEventListener('click', () => {
                    isColSelectedByNum[colNum] = !isColSelectedByNum[colNum];
    
                    //toggle highlight on header
                    if (isColSelectedByNum[colNum]) {
                        columnHeader.classList.add('selected');
                    } else {
                        columnHeader.classList.remove('selected');
                    }
    
                    //toggle highlight on column items
                    for (let colNum of colNumbers) {
                        const isColSelected = isColSelectedByNum[colNum];
                        for (let tr of allTrs) {
                            const td = tr.children[colNum];
                            if (isColSelected) {
                                td.classList.add('selected');
                            } else {
                                td.classList.remove('selected');
                            }
                        }
                    }
    
                    //display isColSelectedByNum
                    output1.innerHTML = JSON.stringify(isColSelectedByNum);
    
                    //display itemsByColNum[colNum] for selected colNums
                    let html = '';
                    for (let colNum of colNumbers) {
                        const isColSelected = isColSelectedByNum[colNum];
                        if (isColSelected) {
                            const colStr = JSON.stringify(itemsByColNum[colNum]);
                            html += `${colNum}: ${colStr}<br/>`;
                        }
                    }
                    output2.innerHTML = html;
                });
            }
        });
    
        reader.readAsText(picker.files[0]);
    };
    table {
      border: 1px solid red;
    }
    
    tr {
      border: 1px solid green;
    }
    
    td {
      border: 1px solid blue;
    }
    
    th:hover {
      color: red;
    }
    
    th.selected {
      background-color: yellow;
    }
    
    td.selected {
      background-color: yellow;
    }
    Choose a csv file where all lines have the same number of items.<br/>
    <input type="file" id="demoPick"></input><br/>
    <table id="demoTable"></table>
    isSelectedByNum: <span id="output1">{}</span><br/>
    selected columns:<br/>
    <span id="output2"></span>