window.onload = function (){
let filHenter = document.getElementById("fileUpload");
filHenter.addEventListener("change", grabFileObject)
}
//Task 2, Task 3 and Task 5
function grabFileObject(event){
//Grabs the uploaded file
let file = event.target.files[0];
let filLeser = new FileReader();
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
//Reads the file as text and calls anonymous function on load
filLeser.readAsText(file);
filLeser.onload = function (){
//Splits each line
const lines = filLeser.result.split("\n");
//Loop to iterate through each line
for (var i = 0; i < lines.length; i++){
//Splits each line in an element
lines[i] = lines[i].split(",");
//Saves elements to an object.
lines[i] = {Date : lines[i][0],
Type : lines[i][1],
Location : lines[i][2],
Amount : parseFloat(lines[i][3])}
}
console.log(lines);
totalNumberOfLocations(lines);
totalNumberOfTypes(lines);
calculateDate();
}
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var output = document.getElementById("output");
output.innerHTML = "";
output.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
}
}
}
//Task 4.1
function totalNumberOfLocations(array) {
const unique = {};
array.forEach(item => (unique[item.Location] = item));
console.log('Total Number of Locations are: ', Object.keys(unique).length);
}
//Task 4.2
function totalNumberOfTypes(array) {
const unique = {};
array.forEach(item => (unique[item.Type] = item));
console.log('Total Number of Types are: ', Object.keys(unique).length);
}
//Task 4.3
function calculateTransactions(array) {
let totalAmount = 0;
let max = 0;
let min = null;
let minDate = null;
let maxDate = 0;
console.log("Total amount is: ", totalAmount.toFixed(2));
console.log("Average amount is: ", average.toFixed(2));
console.log("Maximum amount is: ", max);
console.log("Minimum amount is: ", min);
}
//Task 4.4
function calculateDate(array) {
const date1 = new Date("2018-11-15");
const date2 = new Date("2018-12-4");
// To calculate the time difference of two dates
const Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
//To display the final no. of days (result)
console.log("Total number of days between dates \n"
+ date1 + " and \n"
+ date2 + " is "
+ Math.round(Difference_In_Days) + " days.");
}
https://jsfiddle.net/52kcyvbx/
У меня есть задание, в котором я должен прочитать загруженный файл CSV, используя опцию type = "file" в HTML. Затем данные читаются в JavaScript и отображаются в консоли и в виде таблицы HTML. Мне удалось закончить ту часть, где я должен читать файлы и сохранять каждую транзакцию в массиве объектов. Мой вопрос сейчас заключается в том, как рассчитать статистику для этих транзакций.
В настоящий момент я пытаюсь достичь общей, средней, максимальной и минимальной суммы для всех транзакций (независимо от физического местоположения или типа транзакции). ). Как вы можете видеть в коде, я уже начал объявлять некоторые переменные. " функция CalculateTransactions "
Вот файл CSV, который я использую: https://raw.githubusercontent.com/xZyph/prog1_oblig3/master/data.csv