Adapting my JavaScript code to handle one-dimensional CSV data instead of the usual two-dimensional format

How can I effectively parse this CSV file using JavaScript?

1363085391,42.890000000000,5.432200000000
1363088879,47.570000000000,4.981800000000
1363120475,56.560000000000,1.768000000000
1363132522,53.000000000000,1.000000000000
1363214378,48.630000000000,4.000000000000
[...]

This displayed data provides a detailed history of bitcoin prices and trade volumes for the Canadian dollar. However, due to the extensive list containing every single trade, I am attempting to condense it from hundreds of daily data points to one each week. Essentially, I aim to simplify the data by aggregating volume and averaging price over specific time intervals. This approach is expected to enhance the appearance of the line in the provided line chart.

Unfortunately, the current script is ineffective; it operates under the assumption that the CSV file is a two-dimensional array when in reality, it seems to be one-dimensional. How can I modify the script to ensure accurate parsing of the CSV data?

function simplifyData(data_set) {
  interval_length = 3600; // hourly intervals

  last_price = 0;
  idx = 0;
  while (idx < data_set.length) {

    // reset value for this interval
    volume = 0;
    price_sum = 0;
    count = 0;
    timestamp = data_set[idx]['timestamp'] + interval_length;

    // get sums for this interval
    while (data_set[idx]['timetamp'] < timestamp) {
      volume += data_set[idx]['volume'];
      price_sum += data_set[idx]['price'];
      count++;
      idx++;
      if (idx >= data_set.length)
        break;
    }

    // get average price
    price = count > 0 ? price_sum / count : last_price;
    last_price = price;

    // add new row to monotized data array
    monotized_data.append([
      timestamp: timestamp,
      volume: volume,
      price: price
    ]);
  }
}

// Format: time (UNIX timestamp), price, amount traded
// http://api.bitcoincharts.com/v1/csv/localbtcCAD.csv.gz
var complexCadCsv = "1363085391,42.890000000000,5.432200000000
1363088879,47.570000000000,4.981800000000
1363120475,56.560000000000,1.768000000000
1363132522,53.000000000000,1.000000000000
1363214378,48.630000000000,4.000000000000
...
";

var finalOutput = simplifyData(complexCadCsv);

$(".new_csv").append(finalOutput);

<!--<script src="https://rawgit.com/evanplaice/jquery-csv/master/src/jquery.csv.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>New simplified CSV</h1>
<div class="new_csv"></div>

Answer №1

data_set is in string format, but the simplifyData() function is treating it as an array of objects. To resolve this, you must first convert it into an array.

data_set = data_set.split('\n').map(line => {
    var linearray = line.split(',');
    return {
        timestamp: parseInt(linearray[0], 10),
        price: parseFloat(linearray[1]),
        volume: parseFloat(linearray[2])
    };
});

Also, ensure that when calling monotized_data.append, you use curly braces instead of square brackets and utilize the push() method.

    monotized_data.push({
      timestamp: timestamp,
      volume: volume,
      price: price
    });

function simplifyData(data_set) {
  interval_length = 3600; // hourly intervals

  last_price = 0;
  idx = 0;
  
  monotized_data = []
    
  while (idx < data_set.length) {

    // reset value for this interval
    volume = 0;
    price_sum = 0;
    count = 0;
    
    // Format: time (UNIX timestamp), price, amount traded
    //   timestamp: data_set[idx][0]
    //   price:     data_set[idx][1]
    //   volume:    data_set[idx][2]
    
    timestamp = data_set[idx][0] + interval_length;

    // get sums for this interval
    while (data_set[idx][0] < timestamp) {
      volume += data_set[idx][2];
      price_sum += data_set[idx][1];
      count++;
      idx++;
      if (idx >= data_set.length)
        break;
    }

    // calculate average price
    price = count > 0 ? price_sum / count : last_price;
    last_price = price;

    // add new row to the monotized data array
    monotized_data.push({
      timestamp: timestamp,
      volume: volume,
      price: price
    });
  }
}

// Original CSV Data with timestamps, prices, volumes
var complexCadCsv = `1363085391,42.890000000000,5.432200000000
...
... (truncated for brevity)

// Parse the multi-line CSV string above into a 2D array
var complexCadCsvArray = $.csv.toArrays(complexCadCsv);

...

$(".new_csv").text($.csv.fromObjects(monotized_data));

// Display the original CSV output using jquery-csv
$(".existing_csv").append(complexCadCsvArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/evanplaice/jquery-csv/master/src/jquery.csv.min.js"></script>
<h1>New simplified CSV Output</h1>
<pre class="new_csv"></pre>
<h1>Original CSV Processed through <a href="https://github.com/evanplaice/jquery-csv">jquery-csv</a></h1>
<pre class="existing_csv"></pre>

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

Synchronization issues arise when attempting to update the localStorage

Whenever I switch to dark mode, the update doesn't reflect in _app unless I have two tabs opened and trigger it in one tab. Then, the other tab gets updated with dark mode toggled, but not the tab where I pressed the toggle. I am using useSettings in ...

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

Secure User Authentication using HTML and JavaScript Box

In the given code, I am attempting to implement a functionality where a message is displayed next to the select box if it does not have a value of male or female. This message should not be shown if one of these values is selected. However, this feature ...

Is there a way to utilize a JavaScript function to transfer several chosen values from a select listbox to a different listbox when a button is clicked?

Is it possible to create a functionality where users can select multiple values from a first list and by clicking a button, those selected values are added to a second list? How can this be achieved through JavaScript? function Add() { //function here ...

Discovering the keycode for the GO button in JavascriptDiscovering the keycode

Can anyone help me figure out how to find the keycode for the GO button using Javascript in an Android browser? ...

Employing Ajax.Updater to retrieve a javascript file (prototype.js)

My ajax request is set up as follows: new Ajax.Updater({ success: 'footer' }, '/dyn/actions/checkSystemMessage', { insertion: 'after', evalScripts: true }); The content found at /dyn/actions/checkSystemMessag ...

What is the best way to toggle a div and dynamically load content into it while it's open?

I am looking to create a toggle effect where a div opens, loads a page within it, and then can be closed again. My goal is to achieve this functionality with multiple links on the page. <div id="main-nav"> <div id="menu-container"&g ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

The key to creating efficient routers in Express: Don't Repeat Yourself!

Currently, I am in the process of developing a web application in the form of a network structure that involves basic CRUD operations. However, I am facing the issue of having overly large router files, prompting me to consider splitting them up. One of t ...

Is there a way for me to connect to my Firebase Realtime Database using my Firebase Cloud Function?

My current challenge involves retrieving the list of users in my database when a specific field is updated. I aim to modify the scores of players based on the structure outlined below: The Realtime Database Schema: { "users": { &quo ...

Steps for showing an error prompt when input is invalid:

In my Vue 3 application, I have implemented a simple calculator that divides a dividend by a divisor and displays the quotient and remainder. Users can adjust any of the four numbers to perform different calculations. <div id="app"> <inp ...

Adjust image size dynamically while keeping the original aspect ratio

Is there a way to scale variable portrait and landscape images dynamically to fit proportionally within a browser window? You can find my current image resizing attempt here: http://jsfiddle.net/6pnCH/4/ I would like the image to be already scaled vertic ...

Tips for showing HTML content in an Angular UI grid

I've been attempting to showcase HTML within the grid by checking out this resource: Add html link in anyone of ng-grid However, my attempts led me to this code snippet: var app = angular.module('myApp', ['ngGrid']); ...

Using JSON to bind values to an array of checkboxes

I am working with an array of checkboxes that are populated from a collection. Here is the code snippet: <div class="form-group"> Select days in a week : <td class="even" *ngFor="let item of dayList"> <input value="{{item.check ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

Check to see if the ContentEditable div is currently focused

I'm struggling to determine if a contenteditable div has focus with my current code. Here is what I have so far: if ($("#journal-content:focus")) { alert("Has Focus"); } else { alert("Doesn't Have Focus"); } The issue I'm encounter ...

Updating default values in reactive() functions in Vue 3: A step-by-step guide

Currently, I am in the process of developing an application using Nuxt 3 and implementing the Composition API for handling async data. The specific scenario I am facing is this: I have a page that displays articles fetched from the database using useLazyFe ...

Exploring different sections of the website

I am looking to create a seamless navigation experience between controls on a webpage. Below is an example code snippet that outlines the functionality where a user can click on any component and be directed to another controller. Sample code: const app ...

Creating Angular UI states with parameters in TypeScript

My Understanding In my experience with TypeScript and angular's ui state, I have utilized "type assertion" through the UI-Router definitely typed library. By injecting $state into my code as shown below: function myCtrl($state: ng.ui.IStateService){ ...

Managing React state with custom objects

We are currently utilizing a react table component that requires selections to be maintained across different pages. To achieve this functionality, we have implemented a Map to store the selected rows and a custom class named Selections to manipulate these ...