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

Does Vue trigger v-bind when referring to a component?

My upload component is set up to submit after a message has been sent. Within this component, there is an action that specifies the request URL using v-bind. However, I've noticed that whenever I try to access the reference, the v-bind does not seem t ...

Retrieve fresh results from the search field after inputting data (nuxt, vuex)

I am currently facing a challenge with updating the search results after a user performs a new search in my Nuxt Application. The search query specifically targets users based on postcode, and all relevant data is stored in the store. Below is the code sni ...

Guide to incorporating a variable into the hyperlink function with Google Apps Script

Currently, I am utilizing Google Apps Script to create customized reports within Google Sheets. Within my spreadsheet, there is a column consisting of numbers that I would like to transform into hyperlinks. The URL for each hyperlink is mostly the same, wi ...

The exception handling in Vue JS (router.beforeEach) encountered an issue while trying to convert the exception

I'm currently utilizing router.beforeEach in conjunction with localStorage. The goal is to bypass the homepage if there is data stored in localStorage, and only enter the homepage if there is no data present. Although I can successfully print the data ...

What could be the reason for parent props not updating in child components in VueJS?

Hello, I am new to VueJS and encountering an issue. In the main.js file, I am passing the user variable to App.vue using props. Initially, its value is {} The getLoginStatus() method in main.js monitors the firebase authentication status, and when a user ...

After using `setAttribute`, React is unable to produce any audio

Currently, I am facing an issue with a React component where it should play sound from an array of IDs stored in the database by setting the ID to the src attribute for the source tag. However, this functionality is not working as expected. Interestingly, ...

The functionality of the ajax hash navigation feature seems to be malfunctioning

I've been trying to use hashes for my navigation, but everytime the page loads, my script resets the initial hash to #home. It doesn't matter what hash I add in the URL: Here is the script that runs to check if the hash exists and what content t ...

Exploring the method of accessing one Vue plugin from another plugin with the use of Vue.prototype

I'm currently working on developing a Vue plugin aimed at simplifying the management of authentication state throughout my application. This particular plugin will require interaction with other Vue plugins such as vuex, vue-router, and vue-apollo (fo ...

karma: Error: Unable to access the 'prototype' property of an undefined object

Whenever I attempt to inject my service, the following error occurs: (function () { describe('Test', function () { var $scope, $state, service,ctrl; beforeEach(function() { module('moduleApp'); ...

JQuery implementation of Axis webservice call

Trying to invoke my Axis webservice with the code below var wsUrl = "http://localhost:8080/TestServ/services/TestCls?wsdl"; var soapreq = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cod=\"http:// ...

Using touch-action to enable movement from the last item to the first item in HTML/C

Currently, I am utilizing the touch-action property in my carousel which auto slides without any issues. However, I am facing a problem where when I scroll using touch-action, it stops at the last slide instead of looping back to the first slide. My goal i ...

How can I conditionally disable a button in Vue.js using an if statement?

Can someone help me figure out why all my buttons are getting disabled when I only want one to be disabled? Here is the code where I created a counter with vue.js: <body> <div id="app"> <button @click="co ...

Updating a particular column in a table with Jquery

In this table : $('#listview-table tr').each(function() { var status_id = $(this).find(".listViewEntryValue").$('[data-name~="cf_1525"]').text(); alert(status_id); }); <table id="listview-table" class="table listv ...

Typescript does not allow for extending an interface with a data property even if both interfaces have the same data type

I've encountered a peculiar problem with Typescript (using Visual Studio 2012 and TypeScript v0.9.5) that I could use some help clarifying. The code snippet below functions correctly: interface IA { data: any; } interface IB { data: any; } ...

Ideal Setup for OctoberCMS using Laravel, Vue.js, and Tailwind CSS

As a newcomer to OctoberCMS, I've noticed there are limited tutorials available online. I'm curious about the best setup or possible configurations that can be used with this web technology. We have a specific project requirement which dictates ...

Employing passport-steam alongside sails-generate-auth

As I develop my SailsJS application, I am aiming for users to authenticate solely through Steam. I utilized `sails-generate-auth` to set up some boilerplate code with sails routes, but integrating passport-steam has proven challenging. If you are interest ...

Setting up a custom function for the cancel button in Angular X-editable

Can this be done? I've got a code snippet that resembles the following: <div class="popover-wrapper"> <a class="glyphicon glyphicon-time" ng-if="activity.type === 'continuous'" ng-style=" { 'border': 'none', ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

Retrieving a specific attribute pair from a JSON object

Currently, I am trying to retrieve the temperature data and display it on my webpage. Since these are objects with no specific order, I am struggling to understand how to access them without using an index. { "response": { "version": "0.1", "termsofServic ...

Converting user IDs to usernames in discord.js

I'm currently developing a bot and I want to implement a feature where every time a command is used, it logs the action in the console. Here's the code snippet I've been working on: console.log(message.author ++ ,`used the comman ...