Maximize the sum of diverse numbers effectively

I have an array that contains objects structured like this:

[
  {
    "id": 91,
    "factor": 2,
    "title": "Test Product",
    "price": 50,
    "interval": 1,
    "setup": 0,
    "optional": false
  },
  {
    "id": 92,
    "factor": 1,
    "title": "Another Test Product",
    "price": 95,
    "interval": 1,
    "setup": 99,
    "optional": true
  },
  {
    "id": 93,
    "factor": 1,
    "title": "Just Another Test Product",
    "price": 12,
    "interval": 1,
    "setup": 0,
    "optional": false
  }
]

Now, I want to calculate the following sums:

  • Total setup cost
  • Total price
  • Price total for products based on intervals (grouped by 1, 2, 3, 4, ...)

Currently, I am using computed methods for each calculation:

setupTotal: function () {
            return this.products.reduce ((acc, product) => acc + (parseFloat (product.setup) * parseFloat (product.factor)), 0);
        },

and

monthlyCostsTotal: function () {
            let sum = 0;
            this.products.forEach (function (product) {
                if (product.interval == 1) {
                    sum += (parseFloat (product.price) * parseFloat (product.factor));
                }
            });
            return sum;
        },

and

setupOptional: function () {
    let sum = 0;
    this.products.forEach (function (product) {
        if (product.optional) {
            sum += (parseFloat (product.setup) * parseFloat (product.factor));
        }
    });

    return sum;
},

However, looping through the array multiple times is not efficient.

My question now is how can I improve the efficiency of calculating the following values:

  • Total price
  • Price for optional products only
  • Total setup cost
  • Setup cost for optional products only
  • Price by interval

Answer №1

If necessary, you have the option to take an object and sum.

var items = [{ id: 91, factor: 2, title: "Test Product", price: 50, interval: 1, setup: 0, optional: false }, { id: 92, factor: 1, title: "Another Test Product", price: 95, interval: 1, setup: 99, optional: true }, { id: 93, factor: 1, title: "Just Another Test Product", price: 12, interval: 1, setup: 0, optional: false }],
    result = items.reduce((r, { factor, price, interval, setup, optional }) => {
        r.price += factor * price;
        r.setup += factor * setup;
        if (optional) {
            r.price_optional += factor * price;
            r.setup_optional += factor * setup;
        }
        r.interval[interval] = (r.interval[interval] || 0) + factor * price;
        return r;
    }, { price: 0, price_optional: 0, setup: 0, setup_optional: 0, interval: {} });

console.log(result);

Answer №2

To simplify your code, consider implementing a computed function that would return an object with the desired results:

calculateTotal: function () {
    let optionalTotal = 0;
    let intervalTotal = 0;
    this.items.forEach(function (item) {

        if (item.optional) {
            optionalTotal += (parseFloat(item.cost) * parseFloat(item.quantity));
        }

        if (item.interval === 1) {
            intervalTotal += (parseFloat(item.price) * parseFloat(item.quantity));
        }
    });

    return {
         optional: optionalTotal,
         interval: intervalTotal
    };
};

You can then access these values like so: calculateTotal.optional OR calculateTotal.interval

I hope this solution makes sense for you.

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

How can I put a row at full-width in a Material-UI table in React

I need assistance with displaying data in a table using JSX code: const StudentsTable = (props) => { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple ...

Is there a way to efficiently display more than 10 data items at a time using the FlatList component in react-native?

Here is the data I am working with: singlePost?.Comments = [ 0: {id: 82, content: "Parent1", responseTo: null} 1: {id: 83, content: "Child1", responseTo: 82} 2: {id: 84, content: "Parent2", response ...

Utilizing variables as identifiers in React Native programming

Trying to utilize a dynamic name for a property of an object. For instance, within the function provided below, aiming to use the value stored in the variable 'catagoryId' to access the corresponding child element and assign it to the variable c ...

nodemailer failed to authenticate login: 535 Authentication Error

I'm encountering a 535 Authentication Failed error when trying to utilize the nodemailer npm package in my node application for sending emails through the contact page. My email and password are correct, so I'm unsure why this issue is arising. v ...

The height of the browser action will not return to its original state

I'm currently working on an extension that provides responses based on user text input. However, I'm running into an issue where the height of the browser action won't reset properly. I've tried various methods to fix this problem, in ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

Processing of an array received via AJAX and passed to a PHP script, inside a separate function in a different file

I have a JavaScript array that I am sending via AJAX to a PHP file named aux.php. What I want is for this array to be visible and manipulable within a function inside a class in another PHP file called payments.php. I've provided all the code so they ...

Snippets of the webpage peeking through before the Fakeloader takes over

After implementing fakeloader to preload my content here, I have noticed that my site header often appears before the fakeloader preload animation completes. Is there a way to delay showing the content until the fakeloader is finished loading? Here is the ...

Difficulty in using window.scrollTo within useEffect in reactJS

I'm facing an issue where I am trying to use window.scrollTo on the initial render using the useEffect function. I have stored the vertical offset as an integer in localStorage, but the scrolling is not working and remains at position 0. Problem with ...

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

What is the method for ensuring a variable returns a number and not a function?

I've encountered a perplexing issue that I can't seem to solve. What could be causing the code below to output a function instead of a number? let second = function(){ return 100 }; console.log(second); ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Employing state management in React to toggle the sidebar

A working example of a sidebar that can be toggled to open/close using CSS, HTML and JavaScript is available. Link to the Example The goal is to convert this example to React by utilizing states instead of adding/removing CSS classes. To ensure the side ...

Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with: export const taskSchema = new Schema ({ user:{ type: String, required: true }, project: { type ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

Re-activate external script following a language update in Next.js

In my Next.js 13 app, I have implemented a live chat support button that is dynamically added based on the language selection. The code for rendering the button looks like this: import Script from 'next/script'; ... <div id={`onlinehelp-button ...

Tips for integrating JavaScript code into React JS applications

I am attempting to create a scrollable table that scrolls both horizontally and vertically, using the example provided by . In my project directory under src/components/ScrollExample.js, I have copied and pasted the HTML code. In addition, in src/styles/c ...

What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now. Assuming I have a dummy object structured like this: const dummy = { a: 1, b: 2, c: { d: 3, ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Leveraging Angular js for performing operations in Putty

At the moment, we depend on Putty for connecting to the app server and checking logs. I am looking for a solution that would allow me to automate this process using angular js. Is it possible to send commands from my angular js or any other client-side a ...