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

A guide to accessing items imported from a glb file within the Babylon JS game engine

When I use the BABYLON.SceneLoader.ImportMesh() method to load a .glb file created in Blender, one of the objects is named Cube.003. Surprisingly, after calling the method, Cube.003 is not included in the scene.meshes array. It does show up in the scene ...

WordPress does not recognize the jQuery function

I have encountered an issue with my code where a simple HTML jQuery slider works fine in a standalone file, but when I integrate it into WordPress, it no longer functions properly. The slider is being added to the index.php file by hardcoding the script li ...

Exploring the interaction between nested view controllers and ng-click in AngularJS

There are 8 different jade views, but only one is loaded and filled with jquery into a div that has a controller. I have two questions: Do I need to define the controller again on top of my partial view (the same controller as the main one)? All views h ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Setting the region in Firebase functions is not supported

I have encountered an issue while trying to set a deployment region for my functions. The documentation states that I should use the following code: var functions = firebase.app().functions('us-west2'); However, when I implement this and attemp ...

Utilizing LoopBack Storage Service: Leveraging upload/download functions within JavaScript code

Is there a straightforward way to upload and download files using the storageService.upload and storageService.download functions in my JavaScript/Loopback code? I'm trying to achieve something like this: app.post("/sendFile", (req, res) => client ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

The animation function in A-frame causes entities to vanish when used with D3.js

Working with the animation property in D3.js has been a bit of a challenge for me. When I include the a-animation directly in the HTML section, everything works as expected. <a-box id="box" position="0 1 0" rotation="0 0 0" scale="1 1 1" color="#4CC3D9 ...

Implementing a Scalable Application with React Redux, Thunk, and Saga

What sets Redux-Saga apart from Redux-Thunk? Can you explain the primary use of redux saga? What exactly is the objective of redux thunk? ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...

Error message encountered: React hydrate TypeError - the function __webpack_require_.i(...) is not recognized as a

I encountered a webpack TypeError while attempting to use hydrate() in my index.js file. Strangely, the error does not appear when I use ReactDOM.render() instead of hydrate. My intention behind using hydrate was for server-side rendering. src/index.js i ...

Searching for the row value of specific data within a table using Javascript

I have a PHP table populated with values, and I want to make two of the table data cells editable. The table headers include: Task, Due Date, Staff, and Department. The values in the table data are retrieved from a database using Laravel Eloquent. &l ...

Issue with loading controllers in route files [Node.js]

I've encountered an issue while trying to include a user controller into my routes for a node js app. Everything was working fine until suddenly it started throwing an error message. I've thoroughly checked the code for any potential issues but s ...

Display a Google Map within a modal window following an Ajax request

I'm currently developing a website where I need to display a Google map inside a modal after an AJAX call. The modal is created using Bootstrap, but I'm facing an issue where the map remains blank once the modal is opened. An interesting observa ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

Tips for avoiding Client DOM XSS vulnerability in JavaScript

Upon completing a checkmarx scan on my code, I received the following message: The method executed at line 23 of ...\action\searchFun.js collects user input for a form element. This input then passes through the code without proper sanitization ...

Vue JS sorting elements and reverting back to their original state

Within my Vue application, I have a list of results that I want to sort alphabetically after performing a search. However, I also need the ability to revert back to the original order, which is based on relevancy in my case. The 'relevancy' orde ...

Tips for labeling subplots in PLOTLY JS

Looking for some guidance on adding titles to plots in Plotly JS. I've checked out the documentation but couldn't find anything helpful. Any tips or suggestions would be greatly appreciated! ...

Strangely glitchy navigation bar using jQuery

Over at this website, there's a top navbar that shrinks using jQuery when scrollTop exceeds 100px. The functionality works as intended, but there's an annoying stutter issue where the navbar starts jumping up and down erratically after slight scr ...