Guide on adding the result of two functions into an array using javascript-vuejs

Hello! I'm currently facing an issue where I need to add two functions and store the sum in another array. Should I keep the revenue as an array or is it fine to leave it as a function? I was also thinking about setting numa in a function as an array due to that button. Moreover, when I try to combine this.functionA+this.functionB, the result shows up as ,. Essentially, my goal is to calculate the revenue for each month by adding a button and creating arrays to input the results and then display them. Here's the code snippet:

export default{
name: 'Home',
data(){
    return{
        FormData: {
            revenue:[
                {
                    lollipops:[
                        {
                            lolliSold:0,
                            pricePerLolli:0,
                        }
                    ],
                    chocolate:[
                        {
                            numchocoSold:0,
                            pricePerChoco:0,
                        }
                    ],
                    numa:0,
                    oprod:0
                }
            ] }}
computed: {
   lolliesSale(){
        let SaleArray=[];
        this.FormData.revenue.forEach((ItemL, indexL)=>{
            SaleArray[indexL]=ItemL.lollipops[0].lolliSold+ItemL.lollipops[0].pricePerLolli;
        });
        return SaleArray;
    },
    chocolateSale(){
        let choSaleArray=[];
        this.FormData.revenue.forEach((ItemC, indexC)=>{
            choSaleArray[indexC]=ItemC.chocolate[0].numchocoSold*ItemC.chocolate[0].pricePerChoco;
        });
        return choSaleArray;
    },
    numaSupport(){
        let numaSuppArray=[];
        this.FormData.revenue.forEach((ItemN, indexN)=>{
            numaSuppArray[indexN]=ItemN.numa;
        });
        return numaSuppArray;
    },
    revenue(){
    //return this.<anyfunction>; <- this is ok!!!!
    }

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

Answer №1

Alright, let's start by setting up an empty array called monthlySales: [], Every month, add the total sales to the array and reset the total sales to zero. This same process can be done for any other items in stock. Lastly, use a v-for loop to iterate through each item in monthlySales and display them on the webpage using {{item}}

Answer №2

It appears that the goal here is to monitor total revenue and sales of specific items.

It seems unnecessary to use arrays in the data - individual variables for each tracked item should suffice.

Data() {
return {
chocPrice: 5,
lolliPrice: 5,
otherPrice: 1,
totalRevenue: 0,
lolliSold: 0,
chocSold: 0,

Include a button that triggers a method.

<button v-on:click="buyChocolate">Buy Chocolate</button>

For every chocolate or lollipop sold, activate a method to increase total revenue by the corresponding price and adjust the number of items sold.

chocSold++, totalRevenue = totalRevenue+chocPrice
.

Subsequently, display these values on the page using {{totalRevenue}}

Answer №3

When computing the array in the numa function, it is not necessary since I only have one numa for each year (which equals other income). Therefore, in the revenue section, I refer back to the previous functions using the corresponding index position that signifies the array's location.

export default {
    name: 'Home',
    data() {
        return {
            FormData: {
                revenue: [
                    {
                        lollipops: [
                            {
                                lolliSold: 0,
                                pricePerLolli: 0,
                            },
                        ],
                        chocolate: [
                            {
                                numchocoSold: 0,
                                pricePerChoco: 0,
                            },
                        ],
                        numa: 0,
                        oprod: 0
                    }
                ]
            }
        }
    },
    computed: {
        lolliesSale() {
            let SaleArray = [];
            this.FormData.revenue.forEach((ItemL, indexL) => {
                SaleArray[indexL] = ItemL.lollipops[0].lolliSold + ItemL.lollipops[0].pricePerLolli;
            });
            return SaleArray;
        },
        chocolateSale() {
            let choSaleArray = [];
            this.FormData.revenue.forEach((ItemC, indexC) => {
                choSaleArray[indexC] = ItemC.chocolate[0].numchocoSold * ItemC.chocolate[0].pricePerChoco;
            });
            return choSaleArray;
        },
        revenue() {
            let revenueArray = [];
            this.FormData.revenue.forEach((rItem, indexR) => {
                revenueArray.push(this.lolliesSale[indexR] + this.chocolateSale[indexR] + this.FormData.revenue[indexR].numa);
            });
            return revenueArray;
        }

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

My Java program is receiving unexpected zeros at the end of my arrays

When I output my array long pair[], I noticed that zeros are being added to empty slots. What could be causing this issue? Any assistance would be greatly appreciated. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { dif ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

Deletion of input is not permitted

Currently, I have a telephone input field on my form that only allows numbers. I have implemented a simple JavaScript code to enforce this validation. However, the issue I am facing now is that the input box cannot be deleted. <form id="aylikal" action ...

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

Changing an array into a list using javascript

function convertArrayToList(inputArray) { let list = null; for (let i = inputArray.length - 1; i >= 0; i--) { list = { value: inputArray[i], rest: list }; } return list; } let result = convertArrayToList([10, 20]); console.log(JSON.stringi ...

Tips for utilizing SlowCheetah to modify array elements within a Json configuration file

Today is my first time working with SlowCheetah to transform a JSON configuration file. I am facing an issue where I cannot figure out how to transform an array of settings. For instance, if my original config file contains the following setting: { "Set ...

I need help figuring out how to navigate through Json data that has been transmitted from an Ajax call in

I'm struggling with passing a Json array object to a PHP file using Ajax. I need help on how to properly receive this data and loop through it in PHP. Here is an example of how I'm trying to retrieve the object, named main_data: // The data as ...

Using Javascript Timers in an ASP.NET AJAX application with the pageLoad() function

function initiatePageLoad() { clearTimeout("MessagesTimer"); clearTimeout("NotificationsTimer"); var MessagesTimer = setTimeout("CheckMessages()", 15000); var NotificationsTimer = setTimeout("CheckNotifications()", 15000); } I've be ...

commenting system through ajax across multiple web pages

Experimenting with the webcodo comment system has led me to this URL: Database table: "comments" CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `email` varchar(60) NOT NULL, `comment` te ...

Is there a method to avoid adding @JsonProperties for a boolean field when converting JSON to POJO with Jackson and Spring MVC?

I'm struggling to resolve this problem, but perhaps it's not really a problem after all. My setup involves using Extjs for the front-end and Spring MVC for the backend. The Ajax request appears as follows: {"isOk": true} Here is the Mapping DT ...

Tips for altering Koa's HTTP status code for undeclared paths

If an undefined route is accessed on a Koa server, what is the best method to change the default HTTP status code and response body? Currently, Koa returns a 404 status and 'Not Found' text in the body. I intend to modify this to 501 (Not implem ...

Interacting with an iframe element using Selenium in Python

I have a webpage with an iframe embedded, and I'm using Selenium for test automation: <iframe class="wysihtml5-sandbox" security="restricted" allowtransparency="true" frameborder="0" width="0" height="0" marginwidth="0" marginheight="0" style="dis ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

Tips for choosing Week Range values with Selenium WebDriver

Currently, I am working with Selenium WebDriver and I am trying to figure out how to select week range values from a dropdown menu at once. I have a dropdown called Period, which, when selected, automatically reveals additional dropdowns for From week and ...

href variable for server-side data table

Currently, I am implementing the server-side datatables plugin using an example from http://datatables.net/examples/data_sources/server_side.html While the example works well, I find myself needing to modify the code for my table to better suit my desired ...

Retrieve a specific data point from a Twitter JSON object

Event:header:{timestamp=1446624314000}body: {"filter_level":"low","retweeted":false,"in_reply_to_screen_name":null,"possibly_sensitive":false,"truncated":false,"lang":"en","in_reply_to_status_id_str":null,"id":661816460197675008,"in_reply_to_user_id_str":n ...

AngularJS - Optimizing Video Loading Time

My template is set up to load details via a JSON file, including a video embed. While everything from the JSON files is working perfectly, I'm encountering an issue where the same video appears on every item. Is there a way to assign individual videos ...

Displaying data stored in a database using JSON format with Ember

I seem to be facing a challenge once again. Let me elaborate on what I am trying to achieve. Within the teammembers template, I aim to display information about Team Members and their details from a specific team by joining 3 tables. Here is an example o ...

Retrieve and compute a data point from a JSON web address

I'm looking to calculate the value of my 0.128 litecoin in euros. How can I determine the euro price by multiplying it with 0.128? <!DOCTYPE html> <html lang="en"> <head> <title>Using JavaScript to retrieve JSON data from a UR ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...