Skip to content
Advertisement

How do I print just the first and second element of an array?

I have an array called tagline that looks like this:

[" Leger Poll", " Web survey of 2", "test", "test", "test", "test"]

it is pulled from an external CSS file. I have assigned it a variable name tagline.

I want to print the first and second elements using document.getElementById so that I can style the text. I am not sure why this is not working? I tried pulling the variable outside of the main function so that it would be global but still not working. I am a beginner coder. Here is what I have. Please help.

    var tagline = [];


    async function getData() {
      // const response = await fetch('testdata.csv');
      var response = await fetch('data/test3.csv');
      var data = await response.text();
      data = data.replace(/"/g, "");
      var years = [];
      var vals = [];

      var rows = data.split('n').slice(1);

      rows = rows.slice(0, rows.length - 1);
      rows = rows.filter(row => row.length !== 0)

      rows.forEach(row => {
        var cols = row.split(",");
        years.push(cols[0]);
        vals.push(0 + parseFloat(cols[1]));
        tagline.push(cols[2]);
      });

      console.log(years, vals, tagline);
      return { years, vals, tagline };


    }
    var res = tagline.slice(1);
    document.getElementById("demo1").innerHTML = res;
    var res2 = tagline.slice(2);
    document.getElementById("demo2").innerHTML = res2;


  </script> ```

Advertisement

Answer

It seems You defined the function getData() but you didn’t call it to execute.

Since you use Async function, I am using then().

var tagline = [];

async function getData() { ...// your function }

getData().then(() => {

    const res = tagline[0];
    document.getElementById("demo1").innerHTML = res;

    const res2 = tagline[1];
    document.getElementById("demo2").innerHTML = res2;

});

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement