1

Im trying to load csv file in React and then format it to be saved as a string with line breaks. The problem is this: After this code block:

makeArrayString() {
  let array = this.state.tempData;
  let finalArray = [];
  array.forEach(function(element) {
    let joinedEl = element.join(",");
    finalArray.push(joinedEl + "\n");
  });

The console output looks like this:

0: "5.1,3.5,1.4,0.2,setosa↵"
1: "4.9,3,1.4,0.2,setosa↵"
2: "4.7,3.2,1.3,0.2,setosa↵"
3: "4.6,3.1,1.5,0.2,setosa↵"
4: "5,3.6,1.4,0.2,setosa↵"

I cant send this kind of format to python script on server because of the ↵ char. However when this block of code gets executed:

finalArray = finalArray + "";
finalArray.split("\n").map((item, key) => {
  return (
    <React.Fragment key={key}>
      {item}
      <br />
    </React.Fragment>
  );
});
console.log(finalArray);

The data now looks like this:

5.1,3.5,1.4,0.2,setosa
,4.9,3,1.4,0.2,setosa
,4.7,3.2,1.3,0.2,setosa
,4.6,3.1,1.5,0.2,setosa
,5,3.6,1.4,0.2,setosa

Which is just a string thats needed, only those commas at line beginnings stand in the way. The dataset is now one huge string and I cant find a way to remove those commas at line beginnings. Is there a way to get good format by changing any of those steps? Also Im using Papa Parse for reading the csv file with the block:

loadCsv() {
Papa.parse(Iris, {
  header: false,
  download: true,
  dynamicTyping: true,
  complete: results => {
    this.setState({ tempData: results.data });
    //console.log(this.state.tempData);
    this.makeArrayString();
  }
});

}

afalak
  • 481
  • 5
  • 9
  • 1
    `↵` is just the way the console is choosing to represent the newline character. How are you sending it to your server? Depending on whether or not you need to escape it, It should just be a "\n", shouldn't it? – Khauri Nov 22 '18 at 20:09
  • And leading comma is probably coming from here: `finalArray = finalArray + "";`. Which is the same as `finalArray.join(",") + ""`. You should use `finalArray.join("")` instead. – Khauri Nov 22 '18 at 20:12
  • The line `finalArray = finalArray + ""` is needed for the `.split()` function on the next line to work, if I comment it then an error occurs. The extra comma probably happens because of the newline character. Thank you for suggestions, I tried changing the `.join("")` but the output is still not apropriate. – afalak Nov 22 '18 at 23:46
  • No, don't comment it out, change it to `finalArray.join("")`. It will work. `finalArray + ""` is just a (tbh sort of lazy) way of converting `finalArray` to a string. It's equivalent to `finalArray.toString() + ""` and `finalArray.toString()` joins the elements of the array with a comma, hence why you get an extra comma after your newline. – Khauri Nov 23 '18 at 13:53

0 Answers0