Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual varying values. If I can filter out all other data points (snowgem, votecoin, commercium), then the chart should display accurately.

function buildChartData(){
    var pools = {};

    poolKeys = [];
    for (var i = 0; i < statData.length; i++){
        for (var pool in statData[i].pools){
            if (poolKeys.indexOf("zelcash") === -1)
                poolKeys.push("zelcash");
        }
    }

    for (var i = 0; i < statData.length; i++) {
        var time = statData[i].time * 1000;
        for (var f = 0; f < poolKeys.length; f++){
            var pName = poolKeys[f];
            var a = pools[pName] = (pools[pName] || {
                hashrate: []
            });
            if (pName in statData[i].pools){
                a.hashrate.push([time, statData[i].pools[pName].hashrate]);
            }
            else{
                a.hashrate.push([time, 0]);
            }
        }
    }

    poolHashrateData = [];
    for (var pool in pools){
       poolHashrateData.push({
            key: pool,
            values: pools[pool].hashrate
        });
        $('#statsHashrateAvg' + pool).text(getReadableHashRateString(calculateAverageHashrate(pool)));
    }
}

function displayCharts(){
    nv.addGraph(function() {
        poolHashrateChart = nv.models.lineChart()
            .margin({left: 80, right: 30})
            .x(function(d){ return d[0] })
            .y(function(d){ return d[1] })
            .useInteractiveGuideline(true);

        poolHashrateChart.xAxis.tickFormat(timeOfDayFormat);

        poolHashrateChart.yAxis.tickFormat(function(d){
            return getReadableHashRateString(d);
        });

        d3.select('#poolHashrate').datum(poolHashrateData).call(poolHashrateChart);

        return poolHashrateChart;
    });
}

$.getJSON('/api/pool_stats', function(data){
    statData = data;
    buildChartData();
    displayCharts();
});

JSON:

[
{
"time": 1529585412,
"pools": {
"commercium": {
"hashrate": 5189503226.486427,
"workerCount": 4,
"blocks": {
"pending": 0,
"confirmed": 16,
"orphaned": 0
}
}
}
},
...
]
 

Answer №1

@John, Give this code a shot.

Revise the data array by utilizing

data = data.filter((obj) => obj["pools"]['zelcash'] !== undefined)
.

console.log('Updated length: ', data.length, '\n');

// Filtering items
data = data.filter((obj) => obj["pools"]['zelcash'] !== undefined)

// Beautifying new array
console.log(JSON.stringify(data, undefined, 4));

console.log('\nUpdated length: ', data.length);

» Result

New length: 107 

[
    {
        "time": 1529585427,
        "pools": {
            "zelcash": {
                "hashrate": 0,
                "workerCount": 0,
                "blocks": {
                    "pending": 0,
                    "confirmed": 54,
                    "orphaned": 0
                }
            }
        }
    },
    ... (more JSON objects)
]

New length: 26

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

What is the best way to navigate to a new webpage after clicking a button?

Currently, I am experimenting with socket io and node to show two different HTML pages. Here's what I have set up: app.get("/", function(req, res) { res.sendFile(__dirname + "/login.html") }) The scenario involves a user logging in and pressing ...

Remove a data entry from the MySQL database by selecting the corresponding row in the table and utilizing the DELETE function

Is there a way to remove a record from my MySQL database by clicking on a row in a table that is generated using ejs? Below is the code I am currently using to generate the table rows. <% res.forEach(function(item){ %> <tr> ...

Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images. The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the s ...

The error message "Type Error: val.toString is not a function - mysql npm" indicates

I'm encountering an issue with the 'mysql' package in NPM on a nodeJS backend and I'm puzzled by this error message: TypeError: val.toString is not a function at Object.escape (/Applications/MAMP/htdocs/nodeJS_livredor/node_modules/sql ...

Error in vue.js: Unable to call this.$emit as it is not a function

export default { mounted() { setTimeout(function() { this.$emit('onLoad') }, 4000); } } //views/Load.vue I want to redirect to another page after the page has been accessed for 4 seconds. <template> <d ...

Step-by-step guide on inserting a div element or hotspot within a 360 panorama image using three.js

As I work on creating a virtual tour using 360 images, I am looking to include hotspots or div elements within the image that can be clicked. How can I store data in my database from the event values such as angle value, event.clientX, and event.clientY wh ...

What steps can I take to resolve the TypeError in next js where I am unable to set properties of undefined for 'className'?

I've been working on a Next.js project and I've copied some code from CodePen that is used for designing product layouts on an e-commerce website. However, I'm encountering a problem with the following error message: TypeError: Cannot set pr ...

What is the best way to use Shadcn to incorporate a calendar that takes up half of my website?

Currently, I am in the process of developing a scheduling appointment system. My main challenge is getting the calendar to take up half of my page's space. Despite my attempts to adjust its height and width, I have not been successful in seeing any ch ...

Is there a way to retrieve both the items within a specific category and its corresponding subcategories simultaneously?

Presently, I am managing two models for Category and subcategory. The category model provides an array of data as shown below: category = [ {_id: '1', name: 'Appliances', slug: 'appliances'}, {_id: '2', na ...

Navigating to Protected Mobile Platform

I am experiencing an issue with accessing a .NET website with SSL on my Blackberry device. When I try to view the site, I receive the message "HTTP ERROR 403 FORBIDDEN - You're not authorized to view this page. Please try loading a different page". Th ...

Mastering json deserialization in Golang using the generic interface

Currently diving into the world of golang, I find myself faced with the challenge of understanding the empty interface, a common hurdle for many learners before me. To put my knowledge to the test, I'm delving into a large json file generated by Post ...

Is it possible to utilize a field name with a period (".") in my data source when working with ag-grid?

I am encountering an issue with my data source, specifically with fields that have periods in their name. For example: [{ "id": 1234, "OD.name": "Andrew", "OD.age": 21 },{ "id": 1235, "OD.name": "Roofus", "OD.age": 22 }] When I try to b ...

THREE.js: dual scenes sharing identical camera positions

I'm currently working on a project where I have two overlapping scenes. The top scene can be faded in and out using a slider, and users can rotate objects within the scene for a better view. My challenge is to keep the camera position consistent betw ...

How to easily open a search page with just a click on the search field in CodeIgniter?

I am in the process of implementing a search feature in CodeIgniter. My view file is divided into two main sections: Header section, which includes the search bar <?php echo form_open('controller/live_search');?> <div class="toolba ...

How can one elevate the properties of each item's sub-structure to the root level in an array containing object items?

I am working with an array containing objects, each with a specific structure... [{ user: { /* ... more (nested) user data ... */ }, vacation: { id: 'idValue', name: 'nameValue', startDate: 'dateValue', }, }, ...

Utilizing HTTP POST method in vanilla JavaScript with AJAX

Having some trouble sending a post request to my PHP file as it keeps saying 'undefined index'. Here is my JavaScript code: document.getElementById("btn1").addEventListener('click', xh ); function xh(){ xhr = new XMLHttp ...

Upon executing `$('div')`, an empty array is returned

My goal is to retrieve all the div classes on a page using jQuery $('div');. However, the page does not natively support jQuery, so I am loading it through external links until $ === jQuery evaluates to true. Even on Stack Overflow where jQuery ...

Express js routing issue ("Page Not Found")

Why do I receive a "Cannot GET /" message when I access my HTTP server at http://localhost:8000/? I am using Express JS for server-side routing and Angular for client-side. Some sources suggest that this error occurs because I haven't set a route for ...

Parsing DXF files using only plain JavaScript

Currently, I am immersed in a CNC project and aiming to convert DXF files into objects using JS. Initially, I attempted using SVGs but the results were not as expected - instead of shapes, the drawings exported as lines (e.g., a square appearing as four se ...

Create a spectrum of vibrant colors depending on the numerical value

I'm attempting to create a function that generates rainbow colors based on a numerical value. var max = 10000; var min = 0; var val = 8890; function getColor(min, max, val) { // code to return color between red and black } Possible Colors: Re ...