JavaScript is throwing an error because `csv[i]` has not

When I try to import a CSV file using JavaScript, the dataset imports successfully into my program. However, I keep encountering the error csv[i] not defined (line 57). I attempted to add var i = 0; just before that line, but the error persists. Any suggestions on what I can do to resolve this issue?

//
// =============================================================
//      CSV to coll - custom JavaScript code
// =============================================================
//
//      
//
/***************************************************************
        Important Information:
    This JS object serves to import a CSV file and convert it for use within a coll. 
    It also calculates two spreads between open/close and high/low, while providing the minimum and maximum values of each column.
    These minima and maxima can be utilized to set the range of the zmap object down the chain. 

    ****************************************************************/
// =============================================================
//                Inlets and Outlets 
// =============================================================

outlets = 6;

// =============================================================
//                Functions Begin Here 
// =============================================================

/***************************************************************
    This function handles the importing of the CSV file. It skips the first line (header row) and converts lines to strings.
    ****************************************************************/
function importfromfile(filename)
{
  var f = new File(filename);
  var csv = [];
  var x = 0;
  if (f.open) {
    var str = f.readline(); //Skips first line.
    while (f.position < f.eof) {
      var str = f.readline(); 
      csv.push(str);
    }
    f.close();
  } else {
    error("couldn't find the file ("+ filename +")\n");
  }
  /***************************************************************
    1) The CSV data is read into the coll/cellblock 
    2) Spreads between high-low and open-close are calculated and sent out to the coll/cellblock
    3) The maximum value of each column is determined and transmitted to outlet 1
    ****************************************************************/


  var maxtimestamp=0;
  var maxdatavalue=0;


  for (var i=0; i<=csv.length; i++) {
    var a = csv[i].split(","); 
    var timestamp = parseFloat(a[0]);
    var datavalue = parseFloat(a[1]);


    maxtimestamp=(timestamp>maxtimestamp)? timestamp : maxtimestamp; // open overwrites the max if greater
    maxdatavalue=(datavalue>maxdatavalue)? datavalue : maxdatavalue; // open overwrites the max if greater

    outlet(0, x++, timestamp, datavalue); 
    outlet(1, maxtimestamp, maxdatavalue);
    outlet(4, csv.length);
  }
  // The minimum value of each column is determined and sent to outlet 2
  // A bang to outlet 3 ensures the coll is referenced in the cellblock

  var mintimestamp=Infinity;
  var mindatavalue=0;

  for (var i=0; i<=csv.length; i++) {
    var a = csv[i].split(","); 

    var timestamp = parseFloat(a[0]);
    var datavalue = parseFloat(a[1]);
    mintimestamp=(timestamp<mintimestamp)? timestamp : mintimestamp; // open overwrites the min if less
    datavalue=(datavalue<mindatavalue)? datavalue : mindatavalue; // open overwrites the min if less

    outlet(2, mintimestamp, mindatavalue);
    outlet(3, mintimestamp);
    outlet(4, "bang");
  }
}

Answer №1

The following issue needs to be addressed:

for (var i=0; i<=csv.length; i++) {
// -------------^

Remember, array indexes run from 0 to length - 1, not equal to the length itself. Remove the = sign. Trying to access csv[i] when i is csv.length will result in an undefined value. This may cause an error in the loop body when you attempt to call split on it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of two-way data binding seems to be failing when it comes to interacting with Knock

I am currently working on a piece of code that consists of two main functions. When 'Add more' is clicked, a new value is added to the observable array and a new text box is displayed on the UI. Upon clicking Save, the values in the text boxes ...

How to update state value from axios response using useState() and useEffect() hooks in React

While running my test, I noticed that the axios call is properly mocked, but for some reason, setParticipant() never seems to update the value of the participant variable. I suspect this might be due to its asynchronous nature. How can I ensure that the se ...

Angular 2 404 Error persists despite successful retrieval of data from Oracle database using Backend Nodejs URL entered directly into the browser

Recently, I've been working on displaying data in my Angular frontend that is fetched from an Oracle DB connected to my Node backend. When I access the physical API link, the data appears and is displayed in the backend console.log. I'm wonderin ...

What is the best way to remove all selected items in a dropdown menu?

My issue pertains to Angular and Typescript. I am facing a challenging problem with a dropdown menu that has 3 items. The unique aspect is that I am not utilizing the standard select HTML tag; instead, I am using my company's custom toolkit, which ser ...

There appears to be an issue with 'session' being undefined in this JS/Express/Redis setup for session storage

I've been experimenting with using redis for sessions in my express app. This is what I'm doing: server/auth.js import express from 'express'; import uuid from 'uuid'; const router = express.Router(); router.route(' ...

Main React component failing to update when child component's state changes utilizing React hooks

In my 'HOME' parent component, I have a form for creating a new Pool. I am passing the pool array and setState function into the child component. If I do not refresh the page, the parent component does not render the new pool. "HOME" export de ...

KnockoutJS is unable to assign a negative value to an input field

Is there a way to assign the value of an <input> as false? It seems to work fine with true. Data Model: function DataModel(){ self = this; self.Flag = ko.observable(false); }; HTML Code: <input type="text" data-bind="value:Flag"/> ...

React - Why does React fail to update the state when expected? (not retaining)

Hello there, I'm currently working on fetching JSON data from an API and populating it into a table. It seems pretty straightforward but here's where things get tricky – I can see that the "tableData" state is getting updated as new rows are ad ...

provide a promise that resolves to a boolean value

Below is the code I have: const executorFunction = (resolve, reject) => { <script> if ( 1==1){ resolve(true); } else{ resolve(false); } } const myFirstPromise = new Promise(executorFunction); console.log(myFirstPro ...

How can I apply styling to Angular 2 component selector tags?

As I explore various Angular 2 frameworks, particularly Angular Material 2 and Ionic 2, I've noticed a difference in their component stylings. Some components have CSS directly applied to the tags, while others use classes for styling. For instance, w ...

Cross-origin resource sharing (CORS) policy issue arises when the 'Access-Control-Allow-Origin' header is not included in the requested resource, especially when utilizing an iframe in a React

I am trying to link a website to a button using an iframe. This website allows access to all domain names. Below is the code for my button: <Button component={NavLink} activeClassName={classes.activeBtn} to="/searchEngine&qu ...

Image encoded in base64 not appearing on the screen

Hey there, I'm currently working on implementing a jQuery image uploader that generates a base64 code when an image is selected. function readImage(input) { if (input.files && input.files[0]) { var FR= new FileReader(); FR.onload ...

Merge a variety of arrays containing different data types

Imagine we have an array called colorArray = ['B', 'G', 'R', 'A'] and another array named array2 as Uint8Array. How can we concatenate these two arrays together? I attempted to use var newArray = colorArray.concat(a ...

File index with Node.js server for handling files

I currently have a code snippet for setting up a file server that serves files from a static folder named "public1". However, I am facing difficulties in making an HTML page display by default when a user navigates to the IP address in a browser. Although ...

Combining Multiple Pie Charts with a Line Chart in Highcharts

Can anyone provide guidance on creating a chart similar to the one shown in the Highcharts library? https://i.sstatic.net/BoX4i.jpg ...

Difficulty with Bootstrap 4 mobile navbar dropdown feature

<div class="baslik baslik1 baslik2 "> <nav class="navbar bg-light navbar-light navbar-expand-sm sticky-top "> <a href="./index.html" class="navbar-brand"><img src="img/512x512logo.png" ...

Extension for Chrome that switches between active and inactive modes

I have been attempting to create an extension that can toggle the functionality of another specific extension on and off. Despite numerous attempts, I have not been able to find a solution that works effectively. Essentially, my extension displays a popup ...

Is it necessary to store a file on your local device prior to uploading it to a MongoDB database?

Currently, I am in the process of learning how to upload images from my React website to my Mongo database using an express server. Most tutorials I have come across suggest saving the file locally on the express server before transferring it to the Mongo ...

"Revamping the text style of input materials in React JS: A step-by

How can I modify the style of the text field component in Material UI? Specifically, I would like to change the appearance of the text that the user enters. I have attempted to use the Material API, but it has not provided the desired results. Here is an ...