function CSVsum(filename){
var res = [];
//Open the file and split into rows based on linebreaks
var file = fs.readFileSync(filename,{encoding: 'utf-8', flag:'r'}).split('\n');
console.log(file)
//Split each item in table into values.
for (i = 0; i < file.length; i++) {
file[i] = file[i].split(',');
}
//Using linebreaks to split rows creates an empty final value, so use .pop to remove
file.pop()
//Function to transpose rows into columns
const transpose = arr => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < i; j++) {
const tmp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = tmp;
}
}
}
//Run transpose function on file
transpose(file)
console.log(file)
for(let i=0; i<file.length; i++){
let column = file[i];
let columnSum= 0.0;
for(let i=0; i<column.length; i++){
let value = parseFloat(column[i]);
if(isNaN(value) === false){
columnSum += value;
}
}
res.push(parseFloat(columnSum));
}
return res
}
Basically I've written the above function. Its intended function should be to read a CSV, then sum each column. For the exercise, I am not allowed to import anything additional.
The function works for the most part, except the transpose function for some reason adds an additional array object full of 'undefined'. As a result, where the output should be x,y,z it is instead x, y, z, 0. I know I could use .pop to remove the final item, but I've already done that once when I would've rather not used it at all. What am I doing wrong? I managed to achieve the desired result in python with zip(*file) so I'm trying for a similar effect here.
P.S. I know this isn't the best, so if anyone notices anything else in need of improvement please don't hesitate to let me know!