The reduction method in d3 is producing a result of NaN

UPDATE: I have added a JSFIDDLE link and adjusted the original values in this post to match. However, the fiddle is not functioning properly due to the external CSV file. I attempted a solution found on this thread, but was unsuccessful. Nevertheless, you can still view the code.

On my system, the console logs at lines 52-54 display:

dateArray ["10/17/0014", "10/18/0014", "10/20/0014", "10/21/0014"]
frequencyArray [3, 3, 4, 2]
cumulativeFrequencyArray [3, 6, 10, 12]

When the slider is set to 10/19/2014, I want it to show 0 and 6. It seems like I need to find a way to identify dates with no data and either:

  1. Add zero into the frequencyArray?
  2. Have the cumulativeFrequencyArray display its previous index?

I am also concerned about accessing the external CSV file twice, but that's a topic for another discussion :) Thank you!

ORIGINAL: Using D3, I imported a CSV file containing dates:

timeStamp
10/17/14 02:20:15 PM
10/17/14 08:22:35 AM
10/17/14 09:03:18 AM
10/18/14 02:20:15 PM
10/18/14 08:23:35 AM
10/18/14 09:03:18 AM
10/20/14 08:23:35 AM
10/20/14 10:23:35 AM
10/20/14 02:20:15 PM
10/20/14 02:03:18 AM
10/21/14 04:20:15 PM
10/21/14 09:03:18 AM

I created an array of the dates discovered

dateArray = ['10/17/14', '10/18/14', '10/20/14', '10/21/14']

The number of occurrences of each date were counted and stored in another array

frequencyArray = [3, 3, 4, 2];

Additionally, I applied reduce() on frequencyArray to produce a third array with cumulative sums

cumulativeFrequencyArray = [3, 6, 10, 12];

A date slider is used to exhibit the text values of frequencyArray and cumulativeFrequencyArray (when sliding to 10/21/14, the text shows "2" and "12"). The logic involves checking if the slider value matches a value in dateArray, then displaying the corresponding indexOf values from frequencyArray and cumulativeFrequencyArray.

This method works well until reaching a date without a value, such as 10/19/14, which displays "NaN" and "NaN". To handle this scenario, I attempt to change NaN to zero

frequencyArray[indexOfFormattedCurrentDate] = frequencyArray[indexOfFormattedCurrentDate] || 0;

However, instead of showing "0" and "6", the text displays "0" and "NaN". While it successfully replaces NaN in the frequencyArray text, NaN remains in the cumulativeFrequencyArray text.

How can I ensure the cumulativeFrequencyArray text reflects the sum of the preceding values?

Thank you.

Answer №1

The reason for receiving NaN is because of the following scenario:

var index = dateArray.indexOf('a non-existent date')   // Returns -1
var el = cumulativeFrequencyArray[index]                // Results in undefined 
thousandSeparator(el)     // Produces 'NaN' which is a string representation, not the numerical NaN

To avoid this issue, it is recommended to perform a linear search until the element is located or a higher date is found instead of using indexOf. It is also advised to convert dates into numbers rather than treating them as strings

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

"Vue and axios fail to refresh the DOM even after the value has been modified

I am currently working on a loop for uploading files. this.fileUpload.filter((file) => !file.error) .map((file, index_file) => { var formData = new FormData(); formData.append("folderID", id); for ...

Can the Route be modified in Next.js?

I have developed search functionality that navigates to "/search/xxxx", but it is located in the header. Every time I perform a search, the route gets repeated and becomes "/search/search/xxx". Could you suggest any way other than usin ...

Basic inquiries concerning Vue.js and JavaScript

Hey there, I recently developed a small app to practice my Vue skills. However, there are a few features that I would like to implement but I'm not sure how to do it just yet. <div class="container" id="app"> <div class="row"> <d ...

Using the default theme in Material UI5

Could someone please explain how to pass in the default theme in Material UI5? In Material UI6, I used to do it like this: const useStyles = makeStyles((theme) => ({ home: { display: "flex", paddingTop: "8rem", width: ...

Adding together a pandas timestamp with an array filled with timedelta values

Given a start date and an array containing irregular sample values in days, I am looking to use them as the date index for a pandas series. For example: In [233]: date = pd.Timestamp('2015-10-17 08:00:00') Out[233]: Timestamp('2015-10-17 0 ...

Having issues with the jQuery .css function?

I need help with hiding and showing tabs on my webpage based on a successful login. I have tried various methods, such as setting the tab to be hidden by default in the HTML code and then using JavaScript to display it upon login. However, none of these me ...

Numerous perspectives within an angular.js application

Issue I'm currently working on creating a product list with the following initial features: Server-side pagination Server-side filtering I am facing several challenges with my current setup, but the main issue is that I can't figure out how to ...

Update the website's navigation key for improved user experience

Can the navigation key on a website be altered from 'Tab' to another key, such as 'Enter', allowing for the focus to shift to the next element with the corresponding 'tabindex' when the 'Enter' key is pressed? ...

Is there a way to upload the image as byte data rather than a string?

As a beginner in python, I decided to experiment with changing my Instagram profile picture. However, I hit a roadblock when trying to input the image into the program. Here is the code I have so far: from instagram_private_api import Client, ClientCompatP ...

Error message in console: React Form showing "Form submission canceled due to lack of connection" despite successful submission

I am facing an issue with my form in my React app. Even though the form is successfully submitting data to a list of boxes, I received an error in the console. The error message says: Form submission canceled because the form is not connected In my Rea ...

JQuery and Fancybox causing issues when triggered on Internet Explorer 8

I am experiencing an issue with my jQuery code on my webpage. It works perfectly fine in Chrome, but I encounter an error in Internet Explorer 8 specifically in the trigger('click') line. $('#btnd16').click(function(e){ var iiid = ...

How can I code a script to import JSON data into MongoDB database?

I have a JSON file named "data.json" that contains an array of people's names as shown below: "data": [ { { "name":"John", "age":30, } { "name":"Mark", "age":45, } } ] I am ...

Unable to retrieve a string from one function within another function

Three functions are responsible for triggering POST API calls, with the intention of returning a success or failure message to whoever invokes them (Observable<string>). In an effort to avoid repetition, I introduced a new function to retrieve succe ...

Is there a way to identify which paragraph element was clicked and retrieve its innerHTML content using JavaScript?

Hi there! I'm facing an issue where I need my webpage to identify which paragraph was clicked, retrieve its inner text, and then adjust the size of an image accordingly. You can check it out here: http://jsfiddle.net/YgL5Z/ Here is a snippet of my HT ...

Execute a script to display an alert and redirect on Internet Explorer before an error occurs in Gatsby

I am currently operating a Gatsby site through Netlify, and I have encountered a specific error or crash that is only affecting Internet Explorer. In order to address this issue, I want to display an alert to users on IE and then redirect them to the Chrom ...

Creating a simulated RESTful backend using Sinon.js for an Angular.js project

In the process of developing my Angular.js application, I am incorporating RESTful services that utilize the $resource service. While this app will eventually connect to a Java Spring application, I am currently focusing on creating an isolated mock server ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

Determine the Total of a Column in jqgrid

Hey there, I'm looking for a way to calculate the total sum of the "montant" column in my jqgrid and then display it below the grid as "Total: *total amount*". Here is the code for my grid: <sjg:grid id="gridtable" caption="Quittance Payé ...

Storing and Retrieving Mongoose Data Using Nested Schemas, References, and Promise Functions

I have a question regarding saving and retrieving documents with nested schema references in Mongoose. When I try to save a document with nested schema refs, and then retrieve it later, the required nested field is not included unless I populate it in the ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...