Search code examples
javascriptcsvpapaparse

How to parse only first 2 rows of csv with javascript


I am trying to only get first 2 rows of csv and I have no idea how to do it.This gets whole csv data. Here is my code,

<script>
function arrayToTable(tableData) {
    var table = $('<table></table>');
    $(tableData).each(function (i, rowData) {
        var row = $('<tr></tr>');
        $(rowData).each(function (j, cellData) {
            row.append($('<td>'+cellData+'</td>'));
        });
        table.append(row);
    });
    return table;
}

$.ajax({
    type: "GET",
    url: "https://www.quandl.com/api/v3/datasets/LLOYDS/BSI.csv?api_key=xxxxxxxxx",
    success: function (data) {
        $('body').append(arrayToTable(Papa.parse(data).data));
    }
});
</script>

Solution

  • Change this code:

    $(tableData).each(function (i, rowData) {
        var row = $('<tr></tr>');
    

    By inserting an if line:

    $(tableData).each(function (i, rowData) {
        if (i >= 2) return;
        var row = $('<tr></tr>');