``Consolidate array elements to calculate total sums over a specified time duration

I need help with modifying the code below to only calculate the total payments that occurred within the last 24 hours (86400 seconds).

var addr = 't1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU',
  data = [{
    "name": "zelcash",
    "pending": {
      "blocks": [
        "0000000cc8cb614f91c1f2cb97cce10c6fcbcc16a10ed9e209e03b3debafe56e:b7887996c1267949ffcd80773a6512e7df9cce392ba1f76c89f3b5fa974a0c91:99856:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Lana:1529254887651",
        "00000005a9bf4d9b58d031c4868b14645e93a29fa057f3a02547c8cc70ad46e2:7e679e73247e724e707c485dc9111f981e2bf7f19814abadfa7cecfbb897b146:99735:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Del:1529240255922"
      ],
      "confirms": {
        "00000005a9bf4d9b58d031c4868b14645e93a29fa057f3a02547c8cc70ad46e2": "130",
        "0000000cc8cb614f91c1f2cb97cce10c6fcbcc16a10ed9e209e03b3debafe56e": "9"
      }
    },
    "payments": [{

       // Payment data omitted for brevity

    }]
  }]

var totalAmount =
  data[0].payments.
map(payment => payment.amounts). //get all amount object
map(amounts => amounts[addr]). //get amount from addr
filter(price => price). //filter undefined amount
reduce((first, second) => { //sum amount
  return first + second;
});
totalAmount = totalAmount.toFixed(5);
console.log(totalAmount)

Answer №1

You have the ability to implement a filter based on time, specifically targeting the current time minus one day. Take a look at this example:

var addr = 't1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU',
  data = [{...data object here...}];

var oneDayAgoInSeconds = new Date(Date.now()-1).getTime();

var totalAmount =
  data[0].payments.filter(payment => payment.time >= oneDayAgoInSeconds).
map(payment => payment.amounts). // accessing all amounts
map(amounts => amounts[addr]). // extracting amount by address
filter(price => price). 
reduce((first, second) => { 
  return first + second;
}, 0);
totalAmount = totalAmount.toFixed(5);
console.log(totalAmount)

Additional note: I also included a '0' after the return statement in your reduce function to handle potential errors related to empty arrays.

Answer №2

Make sure to apply a filter for payments made in the last 24 hours before initiating the process:

.filter(payment => payment.time > Date.now() - 24*60*60*1000)

The expression Date.now() - 24*60*60*1000 provides the unixtime value from 24 hours ago.

var addr = 't1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU',
  data = [{
    "name": "zelcash",
    "pending": {
      "blocks": [
        "0000000cc8cb614f91c1f2cb97cce10c6fcbcc16a10ed9e209e03b3debafe56e:b7887996c1267949ffcd80773a6512e7df9cce392ba1f76c89f3b5fa974a0c91:99856:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Lana:1529254887651",
        "00000005a9bf4d9b58d031c4868b14645e93a29fa057f3a02547c8cc70ad46e2:7e679e73247e724e707c485dc9111f981e2bf7f19814abadfa7cecfbb897b146:99735:t1QATR1DnhnrKEsv3tUvWzcjFHKEV4GPBZU.Del:1529240255922"
      ],
      "confirms": {
        "00000005a9bf4d9b58d031c4868b14645e93a29fa057f3a02547c8cc70ad46e2": "130",
        "0000000cc8cb614f91c1f2cb97cce10c6fcbcc16a10ed9e209e03b3debafe56e": "9"
      }
    },
    "payments": [...
      
    ]
  }]

var totalAmount =
  data[0].payments.
filter(payment => payment.time > Date.now() - 24*60*60*1000).
map(payment => payment.amounts). //access all amount objects
map(amounts => amounts[addr]). //retrieve amount based on address
filter(price => price). //apply filter if amount is defined
reduce((first, second) => { //sum of amounts
  return first + second;
});
totalAmount = totalAmount.toFixed(5);
console.log(totalAmount)

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

Several attributes in the JSON object being sent to the MVC controller are missing or have a null

I am facing an issue while passing a JSON object to my MVC controller action via POST. Although the controller action is being called, some elements of the object are showing up as NULL. Specifically, the 'ArticleKey' element is present but the & ...

Steps to deactivate the select element in backbone.js

Can someone help me with disabling the select option in my MVC template code using backbone.js? I tried using readonly="readonly" and disable="disable", but it sends null as value and doesn't update my address. <div class="login-register" data-val ...

"Converting an array within a single object into an object: step-by-step

After retrieving a single row of record from MySQL using Node.js and Express.js, I found that the result was returned as an array inside an object. Here is the output of the result: [ { "user_id": 1, "name": "Aravinth", "email ...

The NextJs error message states: "`nextCallback` is not defined as a function

Having trouble setting up Redux with Next.js for the first time. I keep encountering errors no matter what approach I try, and it's becoming difficult to configure properly. It's frustrating to see so many error messages. TypeError: nextCallback ...

Building an Image/Grid system using CSS and Javascript

Currently in the process of constructing a fresh website, I find myself in need of a solution to a particular issue (specifically involving PHP, MySQL, and Zurb Foundation). The challenge at hand is to fashion an image comprised of 1,000,000 pieces, each ...

Display the input text value when the button is clicked

I am a beginner in JavaScript and have created this HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> Upon entering text into the input field and clicking on the submi ...

Access the file from the resources directory in the Glassfish Java application

My Maven Java EE application is encountering an issue. https://i.sstatic.net/9zBKV.png The file path is as follows: ~/Work/appname/WebContent/resources/json/menu.json Upon deployment on Glassfish, the file can be found here: ~/Tools/glassfish4/glassfi ...

How to utilize AJAX in jQuery to retrieve data from an external URL

Seeking a solution to call an external URL that returns JSON response without success on my development server. After exploring various resources like this and this post, I have tried multiple approaches. Currently, the code I am using looks like this: $( ...

A guide on locating and comparing values of specific elements within a JSON object

I'm looking to dive into the world of JSON and coding. My goal is to retrieve a JSON file and flag any values in the "data" field that are below 50 using Python. However, I'm struggling with accessing specific values and converting them to intege ...

I'm curious why my background generator is only altering a portion of the background instead of the entire thing

I've been attempting to create a JavaScript random background changer, but I'm encountering some challenges. The main issue is that instead of changing the entire page's background, it only alters a strip of it. Additionally, I'm curiou ...

Retrieve the session variable established in Script 1 within Script 2 using PHP

In my code, there is a loop that performs various actions. Inside this loop, I have a session counter that increments with each iteration. Since the loop takes about 10-15 minutes to complete, I would like to implement a progress bar to show the user how f ...

What is the best way to save inputted names as properties of an object and assign the corresponding input values as the values of those properties?

I am searching for a way to dynamically build an object where each property corresponds to the name of an input field and the value of that property is the input's value. Here is the HTML structure: <form> <fieldset> ...

What steps do I need to take in order to create functions that are

I have 10 functions with similar structures: function socialMedia_ajax(media){ return ajaxRequest('search/' + media + 'id', media + 'id').then( function(res) { var imgStatus = res[1].length > 0 ? "c ...

How can I ensure that I am correctly choosing specific fields in a Mongoose query?

After carefully reading the documentation that explains how to extract specific fields from an object based on its id, I attempted to implement a similar code. However, I noticed that the output stored in the user variable includes all fields of the indi ...

Java - Converting JSON format

As a beginner in Java, I am exploring ways to transform Json data just like in the following example. I'm unsure whether to use json array, mapper or List for this task Here's the scenario: Input Document: { "data1": "A", ...

Troubleshooting: Groovy Script with JSON Parameter Configuration is malfunctioning

I am attempting to set up an "Extended Choice Config" parameter. I have written my code in the "JSON Parameter Config Groovy Script," but for some reason, it is not showing up on the "build with parameters" screen. I have tried using both regular JSON and ...

"Is there a way to effectively showcase an error message for AJAX requests in a Rails

I'm having trouble getting an error message to display in Ajax using Rails. I've tried multiple approaches, but nothing seems to work. Below is the form where I want to show my errors: #flash-error.flash-error{:style => "display: none"} #fla ...

When a new element is introduced, onmouseenter feature assigns a unique dynamic function variable

I am incorporating elements generated by Javascript using a for loop. My goal is to pass different variables to a function for each element. Check out my code snippet: var thumbnail_box = document.createElement("div"); thumbnail_box.onmouseenter = functi ...

The mongoose library is not throwing any errors, indicating that the database connection has been established successfully

There are no errors in my code and it's a simple mongoose query - const posts = await Post.find(); console.log(posts); res.status(200).json({ status: 'success', results: posts.length, data: { ...

Guide to ensuring that a form's textarea contains a minimum of 12 characters using Bootstrap

I am currently developing a website form where users input their user id, topic, and body. I am utilizing Bootstrap to validate the topic by ensuring it has at least one non-white space character. For the body, it should have a minimum of 12 characters exc ...