Adding up the quantities of elements in an array

I am seeking assistance in automatically calculating the sums of objects retrieved each time I click a button to fetch data. However, I am unsure about how to proceed with this task.

Below is the script responsible for fetching the data every time the button is clicked:

createTrade (zoneId, cycleId) {
  this.getTrade().then(trade => {
    let zone = this.zones.find(zone => zone.id === zoneId);

    zone.cycles.map(cycle => {
      if (cycle.id === cycleId) {
        return {...cycle, ...cycle.trades.push(Object.assign(trade, {
          account: this.accounts.find(acc => acc.id === this.form.accountId)
        }))}
      }
      
      console.log(this.trade.realizedPL);
      return cycle;
    });

    this.form = {
      accountId: "",
      tradeId: null
    };
  }).catch(() => {
    alert('Trade does not exist');
  });
},

Here are the objects that I am able to retrieve. I aim to add all the "realizedPL" values each time new data is fetched by clicking the button.

https://i.sstatic.net/Jodry.png

English is not my native language, so please forgive me if my explanation is confusing. I hope someone can provide assistance. Thank you!

Answer №1

Utilizing array.reduce can greatly improve this scenario. Take a look at the following example:

const totalProfitLoss => data.reduce(
  (subTotal, item) => subTotal + item.profitLoss, // accumulation function
  0 // initial value
);

// Creating sample data for demonstration
const data = Array.from({length: 5}, () => ({ amount: Math.floor(Math.random() * 100) }));

const sum = data.reduce((subTotal, item) => subTotal + item.amount, 0);

console.log(sum);
console.log(data);

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

The png image is not displaying in the browser when using background-image with Webpack

I'm currently working with Webpack and attempting to display a png image in my Firefox browser. The issue I'm facing is that when Webpack compiles, it generates two images in the dist folder. One of these images seems to have an error as it won&a ...

Learn the easy way to automatically generate HTML in a Vue template file

Is there a way to create HTML inside a Vue template without having to do it manually using the VS Code editor? <template> <div class="hello"> <h1>Hello, world!</h1> </div> </template> <script> export de ...

Unable to retrieve embedded link using fetchText function in casperjs

Exploring the capabilities of Casperjs provides a valuable opportunity to test specific functions across different websites. The website used in this scenario serves as a tutorial illustration. An interesting challenge arises with an embed code that cann ...

When attempting to insert, no action occurs with mongoose

Here is the schema I am using: module.exports = function (mongoose) { var playlist = mongoose.Schema({ title: String, artist: String, album: String, time: Date }); return mongoose.model('playlist', pl ...

Verify the presence of data in Firebase using Angular

Currently, I am working on a web project that involves Angular connected with Firebase console. In my service class, I have defined a function to verify if a certain value exists in the database before saving it. However, whenever I call this function in m ...

Why is my snapshot returning null, even though there are values in the Firebase Database?

I am currently facing an issue in my code related to the snapshot. Specifically, I am trying to retrieve the value of quantity from my Firebase Database. Here's a snapshot of my database: https://i.sstatic.net/qN6m4.jpg and https://i.sstatic.net/Gw ...

What is the best way to utilize the each method within jQuery plugins?

I am relatively new to JavaScript and jQuery plugin development, so please bear with me if this question seems silly. I am struggling with a particular aspect of the following plugin script: (function($){ $.fn.test = function(){ var containe ...

Navigating through items and organizing based on several criteria

In JavaScript, I am currently learning about accessing objects and sorting them based on multiple conditions. As a beginner in JavaScript, this may seem like a very basic question to some. My task involves sorting based on the 'status' field. va ...

Is it possible to smoothly switch between two states using just a single animation class?

I am trying to trigger an animation with a single class, and then have that animation play in reverse when the class is removed. To better explain, I have created a CodePen example of my current progress. In the CodePen, you can see that when the class . ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

Retrieve information from a table by utilizing just two specific columns through the power of JavaScript

I am completely new to the world of web development and have been struggling to find a solution. I have a table structured like this: A B C D FullName ABC pqr xyz TelephoneNo 123 RST GHI My goal is to extract data ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

Motion graphics following the completion of a form input

In my HTML, I've created a div container with a form field: <div class="flex_item" id="b_one"> <form id="f_one"> <input id="i_one" type="text"> </form> </div> I'm attempting to change the backgroun ...

Endless loop within useEffect causing app to experience performance degradation

I am currently working on retrieving Routes based on a list from firebase realtime db. Below is the code I have: import { onValue, ref } from "firebase/database"; import React, { useEffect, useState } from "react"; import { Route, Route ...

A new Vue component is regenerated after the creation method is called

I am facing an issue with setting the margin of an image to display it in the center of the page when the image dialog is created. I have calculated the margin in the component's created method and everything seems fine during debugging as the image i ...

Having trouble figuring out the process of mapping and showcasing data within a React application

On my backend server, I have data displaying in the following format: https://i.stack.imgur.com/f0bfN.jpg I am looking to present this data on my frontend react app. I have attempted the following so far- import {useState, useEffect} from 'react&a ...

Execute a function in the background, even if the browser has been shut down

Is it possible to run a JavaScript function in the background, even after the user has closed the browser? I know this can be achieved in android apps, but I'm not sure about JavaScript. ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

Using jQuery to update a label within a checkbox list

I'm facing a challenge in jQuery where I am attempting to dynamically replace labels with hyperlinks. Unfortunately, my current code doesn't seem to be working as expected. My goal is to assign a specific hyperlink to each list item based on its ...

transferring an item through ng-repeat

<td ng-repeat="data in data_legend" rowspan="2"></td> Within this code snippet, the data_legend variable is a dynamic array that users populate through a Form. The goal here is to showcase all the dynamic content to the user and determine whic ...