Home > Software engineering >  Get value after last comma in CSV file in Javascript/HTML
Get value after last comma in CSV file in Javascript/HTML

Time:10-09

Note: I tried using d3js but I accept any other usage model, getting the expected value any method will be positive for me.

Example to file ./Lista_de_Jogos.csv:

a,b,c,d,e,1
f,g,h,i,j,2

I would always like to collect the last value of the CSV regardless of its size, in this example the value would be:

2

My attempt was:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.1/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-fetch@3"></script>

<script>
   function lastvalue() {
      let lastvalue = d3.csv("./Lista_de_Jogos.csv");
      var lastvaluelast = lastvalue.substr(lastvalue.lastIndexOf(',')   1);
      console.log("Last Value: ", {lastvaluelast})
   }
</script>

But I can't get the return of the value, how should I proceed to receive such value?

I've already searched on stackoverflow and couldn't find an example for Javascript/HTML

CodePudding user response:

You need to wait for the promise to resolve. Use then:

function lastvalue() {
    d3.csv("./list.csv").then(result => {
        console.log('result:', result)
        const lastRow = result[result.length - 1]
        console.log('lastRow:', lastRow)
        const lastValue = lastRow[result.columns[result.columns.length - 1]]
        console.log('lastValue:', lastValue)
    });
}

lastvalue()
  • Related