I have a task to read a file with actions and values assigned to the actions. At the end the code is supposed to add some of the values together but also multiply some of the values, in a specific order. But to start with I need to get the code to read the contents of my file as an array. This is what I have so far and I hope to get some help with my next step.
const input = document.querySelector('input')
const fileReader = new FileReader()
fileReader.onload = (e) => {
console.log(e.target.result)
const data = csvToArray(e.target.result)
console.log(data)
}
const csvToArray = (str, delimiter = ",") => {
const headers = str.slice(0, str.indexOf("\n")).split(delimiter)
const rows = str.slice(str.indexOf("\n") + 1).split("\n")
const arr = rows.map((row) => {
const values = row.split(delimiter)
console.log(values)
const el = headers.reduce((object, header, index) => {
headers[header] = values[index]
return object
}, {})
return el
})
return arr
}
input.onchange = (e) => {
console.log(e.target.result)
const [file] = e.target.files
fileReader.readAsBinaryString(file)
}
This code makes the content of my file appear in the console but it displayes the \r at the end of every row. I have tried to add the "\r" where I put the "\n" but realised it was not the way to go. I also tried it with the delimiter but it was not right. How do I remove the \r and create an array I can access with Javascript and loop through it?
My file looks something like this:
