Performing computations within a loop and ways to retrieve the total of the elements in Vue.js

Starting out as a newcomer to JavaScript, I am seeking guidance on how to effectively incorporate it into my current project.

I'm tasked with creating a sophisticated financial calculator within my already existing PHP financial instrument. The goal is to display detailed calculations reactively. I am struggling with implementing complex calculations that involve numerous `if` statements within a loop and then aggregating the output values from each object in an array to return a total sum. I intend to utilize Vuejs for this task.

In essence, my `cashDividends()` function should calculate the sum of values obtained from each object in the loop.

To provide context on the issue at hand, I have included a snippet of the code below:

 new Vue({
    el: "#waterfall",
    data() {
        return {
        info: {
            cash_dividends: true,
            converted_liabilities: true,
        },
        equities: [
            @foreach($preferredEquities as $equity)
            { name: '{{ $equity->name }}', id: {{ $equity->id }} },
            @endforeach
            ]
        }
    },
    computed: {
        remainingExit () {
            return this.form.exit_value - this.form.uncovered_debt - this.form.transaction_fees
        },
        cashDividends() {
    //I supposed should be something like this.     
          this.equities.forEach(function(equity)
          {
            //Here I make a lot of calculations with bunch of if statements using object and DOM input values. for each object 

          }
          // And here I need to return sum of calculated values from each object (equity) in array 
        }
    },

If anyone has any insights or tips to offer, I would greatly appreciate them. I am eager to grasp the overall concept behind this challenge.

Answer №1

If you're looking to calculate a total, using a reduce function would be the way to go.

const total = this.equities.reduce((sum, equity) => {
  const myEquityCalc = << something >>;
  return sum + myEquityCalc;
}, 0)

Check out this Demo:

const equities = [{value: 100}, {value: 200}];

const total = equities.reduce((sum, equity) => {
  return sum + equity.value;
}, 0)

console.log(total)

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 parameter type 'string | null' cannot be assigned to the value function 'ValueFn<SVGPathElement, Datum[], string | number | boolean | null>'

I recently delved into the world of d3 and attempted to create a simple line chart using d3, TypeScript, and react. However, I keep encountering a TypeScript error whenever I try to implement it. Strangely, I can briefly see my chart before it disappears a ...

The issue arises in Laravel when the second summernote instance unexpectedly returns null

I am facing an issue with using two summernotes in the same Laravel form. The value of the second one returns null. It works fine with PHP, but not with Laravel. Below is my code: <textarea class="js-summernote" id="summernote" name="details"></ ...

You can use HTML tags within a script tag for added flexibility and

I'm working on incorporating this into a dynamic script using data from an XML file (aiming for 50% to be dynamic). <div class="progress-bar progress-bar-danger" data-progress-animation="50%" data-appear-animation-delay="20"> It currently func ...

Cannot choose an option using JQuery Select2

Encountering an issue with Select2. The functionality seems to be working fine, except for the inability to select any option. Utilizing select2 version 3.5.3 along with KnockoutJS, CoffeeScript, and JQuery. Here is my select2 code: generateSelect3 =-> ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Guide on executing dynamic queries with MySQL in Meteor

Attempting to execute dynamic queries against MySQL in Meteor using the numtel:mysql package has proven unsuccessful thus far. It seems that either I need guidance on passing dynamic arguments to the subscribe function, or I need to learn how to retrieve ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

Utilize an API call to fetch data and seamlessly showcase it on the webpage using Vue.js

I have created an API and defined it in my TypeScript file const Book = { async getBookType(intID: string): Promise<Book[]> { // const intId = API.Product.getCurrentId(); const intId = ''; const response = await h ...

Guide to displaying a task within a table cell after a user submits the form

<?php $servername = "localhost"; $username = "u749668864_PandaHost"; $password = "Effy1234"; $dbname = "u749668864_PandaHost"; $q = $_REQUEST["task"]; $task = $q; echo $task; $conn->close(); ?> Exploring the world of ajax has left me scratching ...

Vitek - Uncaught ReferenceError: Document Is Not Defined

Why am I encountering an error when trying to use File in my vitest code, even though I can typically use it anywhere else? How can I fix this issue? This is the content of my vite.config.ts. /// <reference types="vitest" /> import { defin ...

Streamline the process of creating and renaming directories within an Express.js application

My goal is to set up a basic Node.js Express website, and I'm executing the following commands: cd node npm install pug express express project_name cd project_name && npm install npm start After running this, the /public folder is being cre ...

The information is not being shown. Error: API expression GET is not possible

import express from 'express'; import data from './data'; const app = express(); app.get("/api/products", (req, res) => { res.send(data.products); }); app.listen(5500, () => {console.log("The server has been successfully s ...

What is a more efficient method for identifying a single, specific object without using the index approach demonstrated here?

I need to verify if the taskDetails object contains only the lastTask value and no other values. To achieve this, I am currently using the approach with index [0] as shown below: Object.keys(this.clubdetails.taskDetails)[0]==["lastTask"] However, I have ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

Identify and click on the child span within the li element using Cypress

I am struggling to select a li element and click/check on the span with the checkbox class, but I can't seem to make it work. Here is what I have attempted: <div id="list-widget"> <ul class="tree"> <li class ...

Traversing through each element using Array method

I need to create a redux function that will add a specified number n to the fourth element of an array every time a button is clicked. However, if the element is either L or M, I do not want the addition to occur. For example, starting with this initial a ...

The ajax request is functioning incorrectly in both Chrome and Firefox

Hey there! I've run into an issue with my Ajax call - it's working fine in Safari but not in Chrome or Firefox. It's strange because everything is running smoothly on my local machine. Could my recent SSL certificate installation be causing ...

Having trouble getting my Sequelize model to export properly

For my school project, I am developing an e-commerce website and encountering an issue with connecting my GoogleStrategy to my SQLite database. The goal is to store user data in a table, but whenever I try to call the variable in my passport-setup file, an ...

Show the outcome of a function inside an ng-repeat loop

I have encountered a roadblock in my Angular project. I am populating a table with run data retrieved from a REST call using ng-repeat. Each run includes GPS coordinates, and I have a function that converts these coordinates into the corresponding city nam ...

Double Checkbox

My current project involves creating an update page, and I have successfully completed most of it except for the checkbox section. Strangely, the checkboxes are being duplicated, and I haven't been able to identify the reason behind this issue yet. Th ...