Tips for getting the sum of an array using the reduce method in Vue.js and returning the result array

As someone new to JavaScript, I apologize if my description of the issue is not clear. It's challenging for me to explain the problem I am facing.

I have a computed function where I use the reduce method to iterate over my objects, perform calculations within the loop to find new variables, and then return an array with the summed values.

I am able to return the sum of a single variable inside the loop, but I'm struggling to return two variables from the computed function. My solution is to convert these two values into an array and somehow return their sum, so that I can use these values in future calculations. Could you please provide some guidance on how to tackle this issue?

 new Vue({
        el: "#demo",
        data() {
            return {
            objects: {
                price: 0,
                amount: 0,
                percent: 0,
                fee: 0,
                solution_cost: {dry:0, wet: 0}
            },
        },
        computed: {
            solutionCost() {
                //Looping through my objects
                const total = this.objects.reduce((sum, object) => {

                    let solution_cost_dry = object.amount / object.price;
                    let solution_cost_wet = object.solution_cost[dry] * object.percent;

                    // Unsure how to sum "dry" and "wet" values and store them in an array
                    return object.solution_cost: sum + {dry:solution_cost_dry, wet:solution_cost_wet  }

                }, 0)

                // Returning an array with the summed values {dry:solution_cost_dry, wet:solution_cost_wet  }
                return total[];
            },
        }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Answer №1

I have marked the code with //UPDATE comments where I made changes to the logic. You must provide an initial object containing the values you wish to return, and then update the nested keys for the totals accordingly.

computed: {
    solutionCost() {
        //Iterating through my objects
        const total = this.objects.reduce((sum, object) => {
            solution_cost_dry = object.amount / object.price;
            solution_cost_wet = object.solution_cost[dry] * object.percent;

            //UPDATE: Incorporate the values into the totals
            sum.dry += solution_cost_dry;
            sum.wet += solution_cost_wet;
            
            return sum;
        }, {dry:0, wet:0}) //UPDATE: Initialize "sum" as an object with zero values for each key

        //return an array with the summed values {dry:solution_cost_dry, wet:solution_cost_wet  }
        return 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

Vue 3 list fails to refresh

Using an API, we are retrieving data: <script setup> import { onMounted, inject } from 'vue' let list = []; function initializeData() { axios .post("/some-link/here") .then((response) => { list ...

Element on webpage "Expands" When Scrolled into Visibility

After posting a question on Stack Overflow, I noticed discrepancies between the element dimensions reported by Chrome Inspector and Selenium WebDriver. While Chrome Inspector showed w = 979, h = 1961, Selenium returned dimensions of 979 and 1461 respective ...

What steps should I take to optimize the performance of this code by implementing rate-limiting for its execution speed?

As I pondered the task at hand, I realized that using a sleep function might be beneficial. However, Javascript lacks a built-in sleep function. How can I tweak this process to avoid hitting a Parse rate-limit? My goal is to execute one (1) Parse.Cloud.ru ...

Changing $scope does not automatically refresh the selected option when using ng-options with <select> in AngularJS

My select element is structured like this: <select ng-model="exportParam" ng-options="item as item.lib for item in allExportParams | orderBy:'lib'" class="form-control"> </select> To save its state for later display, I sto ...

Attach Vue to the body or any other specified element

Many developers choose to bind their Vue instance to the body tag in some cases, while in other situations they opt for binding it to a specific div id. The question arises: when should one use the body tag versus an id tag to limit the scope of the Vue i ...

``Please note that the Sinon spy.called method is currently not

Context In my setup, a small server receives data from a machine. Each time a message is received, a function in a dispatcher object is called, which simply logs everything it receives to the console. Issue While I can see the logs in the console, Sinon ...

Node-express can seamlessly switch between multiple databases dynamically

After extensive searching for a solution to my problem, I have come up empty-handed. If anyone has experience in similar situations, your help would be greatly appreciated. I have developed an application server in Node Express with MySQL as the database. ...

Is there a way to bring together scrolling effects and mouse movement for a dynamic user

If you want to see a scrolling effect, check out this link here. For another animation on mouse move, click on this link(here). Combining both the scrolling effect and the image movement might seem challenging due to different styles used in each templat ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

Encountering a issue when trying to click the Menu icon in a Vue 3 admin template

i recently set up the CoreUI Vue admin template CoreUI Vue Template. Everything seems to be working smoothly, except for the menu icon https://i.stack.imgur.com/tOShL.png. Whenever I try to hide the side bar (which is a built-in feature), it's not fu ...

Error: The PDFJS variable is not recognized when trying to load a PDF file

I've been experimenting with pdf.js to load PDFs into a web application in order to extract information in real-time. However, I keep encountering an error even with a simple example. I've attempted enclosing the code in $(document).ready() as a ...

Utilizing $routeParams to dynamically generate the templateUrl with AngularJS

Our platform offers a 2-level navigation system. We are looking to utilize AngularJS $routeProvider to dynamically load templates into an <ng-view />. Here is the approach I am considering: angular.module('myApp', []). config(['$route ...

"Looking to programmatically close a modal in JavaScript that was opened using the 'data-target' attribute? Here's how you can

I have a modal template embedded in the same HTML file as my controller. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalDeleteItem">Delete selected item</button> < ...

Waiting for a function to finish within a nested function in JavaScript

I'm facing a simple issue that I'm struggling to solve. I have two functions and an object in JavaScript (Node.js) structured like this: var auxmap = new Map(); function one() { for(var i...) { //initialize the map and do something tw ...

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

Are you looking for methods to alter the elements of a webpage prior to viewing it?

I have created a page with the intention of using it as a tool, but I am facing some challenges due to my limited experience in this field. As a newcomer, I am struggling to achieve certain goals: - My objective is to modify the values of an element on a p ...

The challenge of maintaining coherence in AngularJS scopes

It's driving me crazy. Our integration with some ATSs involves sending queries and setting variables in the scope upon receiving responses. I always make sure to set the variables within a $scope.$apply() to ensure proper updating. Everything was work ...

What is the best way to create a toggle effect for a <nav> bar that appears from beneath a div?

I need assistance with a navigation setup where the nav (located inside the header) needs to be connected to the bottom of a div named .menu_bar. The desired behavior is for the nav to slide down from directly underneath the .menu_bar when toggled, but cur ...

What causes AngularJS to generate an error when attempting to construct a URL for the src attribute of an iframe?

Recently, I've been working with AngularJS directives and encountered an issue while trying to use an expression in the src attribute of an iframe. The error message I received referenced a URL that didn't provide much insight: http://errors.ang ...