A step-by-step guide to summing two numbers within a list using vue.js

How do I calculate the average of the first 5 numbers in my list taken from the URL, grouped by 5-minute intervals? I have a delay of 1 minute to ensure there are 5 values within the initial 5 minutes. After that, I want to display the averages in 3 different templates.

<template>
  

<div id="app">
  
 
  <form>
    
    <label>Enter Currency: <input type="text" v-model="currency"></label>
    <input id="clickMe" type="button" value="Submit" @click="getData(currency)" />
    
    
    
    
  </form>
  
  <pre></pre><p>Bitcoin Value is: {{ apiData?.data?.amount }}</p>
  

  <template v-for="value in getShortList(5)">
    <pre></pre><p>Average for last 5 minutes: {{ }} </p>
    <li class="divider" role="presentation"></li>
  </template>

  <template v-for="item in getShortList(29)">
    <pre></pre><p>Average for last 30 minutes: {{parseInt(getShortList(29))}}</p>
    <li class="divider" role="presentation"></li>
  </template>

  <template v-for="item in getShortList(59)">
    <pre></pre><p>Average for last 60 minutes: {{ parseInt(getShortList(59)) }}</p>
    <li class="divider" role="presentation"></li>
  </template>



 

  <template>
<div>
  <apexchart width="500" type="bar" :options="options" :series="amountList"></apexchart>
</div>
</template>



  
</div>



</template>

Script code:


 import axios from 'axios'
 

export default {
  
 
 
  data() {
    return {
      apiEndPoint: 'https://api.coinbase.com/v2/prices/spot?currency=',
      apiData: [],
      amountList: [],
      
       
      
      
      
    
    }
  },
  

  created () {
   


    
    this.getData(this.currency);

   
   
  }
,
 
  

  methods: {
    getShortList(shortListSize) {
      return this.amountList.slice(0, shortListSize);
      
     

    },

    

    getData(currency) {

     
      axios.get(`${this.apiEndPoint}${currency}`).then((response) => {
        
        this.timer = setInterval(() => {
   
        this.apiData = response.data
        this.amountList.push(response.data.data.amount)
        

        console.log(this.amountList)
      }, 5000) 
        })
       
    
  
        
    
      }
      
    }
  }


  


   
</script>

Answer №1

Based on my understanding and your comments, it seems like you are encountering a difficulty in calculating the average of the elements in the array (this.amountList). If this is the case, you can use the Array.reduce() method to accomplish this task.

Check out this example for a Live Demo :

// Array containing 5 items from amountList
const arr = [100, 200, 30, 44, 50];

// Calculate the average
const average = arr.reduce((a, b) => a + b, 0) / arr.length;

// Display the result
console.log(average);

Once you have calculated the average, you can make it reactive by storing the value in a data object property.

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

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...

Submitting a form is disabled when there are multiple React form inputs

I have a simple code example that is working correctly as expected. You can check it out here: https://jsfiddle.net/x1suxu9h/ var Hello = React.createClass({ getInitialState: function() { return { msg: '' } }, onSubmit: function(e) { ...

What steps do I need to take to create a delete button that will effectively remove a bookmark from an array?

Currently, I have created a form that allows users to input the website name and URL. Upon clicking the submit button, the output displays the website name along with two buttons: 1. one for visiting the site 2. another for removing the bookmark using on ...

Employing jQuery to add an element as a sibling rather than a child node

I'm having trouble finding the specific functionality I need. My goal is to add sibling DOM elements to a disconnected node. From what I gather, it should be possible with either .after() or .add(), but for some reason both methods are not working as ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Using TypeScript gives you the ability to specify the type of an object while destructuring it,

Currently in the process of refactoring a NodeJS application to TypeScript. I have been consistently using object destructuring and have also been creating aliases while object destructuring, as shown in the code block below. My question is, how can I sp ...

The validation process fails when the button is clicked for the second time

When adding a username and email to the userlist, I am able to validate the email on initial page load. However, if I try to enter an invalid email for the second time and click the add button, it does not work. <form id="myform"> <h2>Ad ...

Error in Laravel: The source map for js/app.js could not be located, request failed with a status code 404

I recently started using laravel and keep encountering the following error message in the browser console: Source-Map-Error: request failed with status 404 Resource-Address: Source-Map-Address: popper.js.map I'm struggling to pinpoint the ...

Error message "$injector:unpr" occurs in the run method of AngularJS after minification process

I've encountered an issue with angular-xeditable on my Angular app. While it functions properly in the development environment, I'm facing an error in production when all JS files are minified: Uncaught Error: [$injector:strictdi] http://errors. ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...

Tips for transforming a nested for-loop into a recursive function

Trying to work with Memcached data in Node.js is proving to be a challenge due to the asynchronous nature of the language. My goal is to store all retrieved results in an object. This is how I would typically approach it: for( x = startX; x <= endX; x ...

A modern web application featuring a dynamic file treeview interface powered by ajax and php technology

Currently, I am developing a web-based document management system that operates as a single page using an ajax/php connection. The code snippet below shows how I display folders and files in a file tree view: if (isset($_GET['displayFolderAndFiles&apo ...

Module specifier "vue" could not be resolved due to an uncaught TypeError. Remember that relative module specifiers must always begin with "./", "../" or "/"

Looking to create the most basic vuejs Hello World application using separate files. Here is the project setup: start by creating index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Keep an ongoing watch on the presence of a xpath that may become visible at any point on a website

I am currently using a java program to execute selenium tests. However, I am facing an issue where during the midst of the run, there is a possibility that a web message containing the xpath may or may not appear: //*[@id='toast-container'] If ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

Processing one file to submit two forms to the database in Express

I am facing an issue with two forms on one form.hbs page using the same process.js file. Each form is processed by a different submit button for separate occasions. The first submit button works correctly, processing the data in the process.js file and se ...

Ordering a string of whole numbers using JavaScript

I'm currently working on a form that takes a string of numbers, splits them at each semi colon and space, sorts the numbers, and then displays the sorted list. However, when I click the button, the value in the text box doesn't get posted. Can ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

Leveraging multiple routes for a single component in Angular 6

Creating a component named Dashboard for admin requires passing the username in the route to find user information. This is the routing setup: {path:'dashboard/:username',component:DashboardComponent,children:[ {path:'role',component: ...