Deducting the sum of all elements in an array from the initial value

In my current project, I am working with an array of objects structured as follows:

let budgetData = [{title: "Monthly Income", amount: "2500"}, {title: 
"rent", amount: "1000"},{title: "car", amount: "200"}];

I have been attempting to perform some calculations using this data set:

2500 - 1000 - 200 = whatever the result may be. You have the flexibility to keep adding more amounts to the array based on your monthly expenses.

Initially, when you run this calculation with just two values, the outcome matches expectations (e.g., 2 - 1 = 1).

However, if you add more than two amounts to the array, it seems that only the last value is being subtracted from the first one, impacting the accuracy of the final result (e.g., 5 - 2 - 1 = 4).

let amount = [];

for (let i = 1; i < budgetData.length; i++){ amount = 
budgetData[0].amount - budgetData[i].amount;

console.log(amount) === 2300

Despite running the above code with the provided information, the calculated answer turns out to be 2300 instead of the expected 1300.

I would appreciate some insights on where I might be making a mistake in my approach. Additionally, I am curious to know if there exists a built-in math function that can assist me in achieving the desired outcome efficiently.

Answer №1

Every iteration of the loop results in discarding the previous calculation and replacing amount with a new one. Ultimately, this leads to subtracting the final number from the initial number.

To avoid this, you should maintain a cumulative total, like so:

let budgetData = [
  {title: "Monthly Income", amount: "2500"}, 
  {title: "rent", amount: "1000"},
  {title: "car", amount: "200"}
];

let amount = budgetData[0].amount;

for (let i = 1; i < budgetData.length; i++){ 
   amount = amount - budgetData[i].amount;
}

console.log(amount);

Answer №2

Another approach is to decrease the array size:

const finalAmount = expensesData.reduce((first, second) => (first.amount || first) - second.amount);

In case your expense objects have a valueOf method defined like this:

 class Expense {
  constructor(attributes){
     Object.assign(this, attributes);
  }
  valueOf(){ return this.amount;}
}

expensesData = expensesData.map(item => new Expense(item));

The code becomes even more elegant:

const finalAmount = expensesData.reduce((x,y) => x-y);

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

What is the best way to group/merge multiple objects that have the same name into a single object (Nesting)?

I have a dataset containing students' names and their marks in different subjects stored as an array of objects. My goal is to merge the data into a single object for each student with matching names, resulting in one record per student. Here is an ex ...

Having trouble fetching configuration values with Vue.js

console.log(process.env.test); displays "undefined" in the console. In the dev.env.js file, I have the following configuration. Do you see anything that I might have overlooked? 'use strict' const merge = require('webpack-merge') con ...

How to Use a Function to Generate Triangular Shapes in Three.js Using an Array of Vertices

I am diving into the world of JS and THREE.js with the goal of creating a function that performs the following tasks: Combine every 3 values to generate a new vertex, Group every 3 vertices to create a new THREE.Triangle(ta, tb, tc); Keep track of all the ...

React frontend unable to retrieve JSON data from Rails API

I have developed a backend Rails API and confirmed that the endpoint is being accessed by monitoring my server in the terminal. Additionally, I am able to view the response in Postman. However, I am facing an issue where the payload is not returned in my R ...

Error occurred while retrieving JSON array using Jquery

var groupMembers = $.parseJSON(members); $.each(groupMembers, function (index, item) { $.ajax({ type: "POST", url: "'.base_url(" / panel / listNotifications ").'/'.$id.'/" + valueSelected, d ...

Simple Steps for Sorting an Array by 2 Criteria

I am working with an array that consists of various rowsets containing attributes like type, title, and description. My task is to filter this array in order to display only the rowsets that are categorized as "education" or "experience". Looking for a wa ...

Transforming a string that is separated by commas into an array

I've been attempting to convert a string into an array of integers, floats, and characters. While I've managed to make it work for integers and floats, I'm encountering an issue with characters. #include <stdio.h> #include <stdlib.h ...

Transmitting data from JQuery to PHP script

In my current setup, I am utilizing JavaScript to retrieve a JSON array from a PHP file: <script type="text/javascript" language="javascript" > $(document).ready(function() { var dataTable = $('#employee-grid'). ...

Retrieving data using parameters in Javascript

Just a quick overview, I am attempting to retrieve data from a URL using 2 parameters but I have no prior experience with JavaScript. Here is what I have tried: componentDidMount() { $input = array("team" => {teamName}, "name" =& ...

Stop the bootstrap accordion from expanding when a button in its header is clicked

Currently, I am facing an issue with two action buttons located in the header of an accordion. Here is the setup: https://i.sstatic.net/HU2Kp.png Whenever I click on one of these buttons, it toggles the accordion's state. I have attempted to use e.p ...

My preference is to arrange strings in a numerical fashion

Trying to implement a sorting function with an arrow button that inverts for exam scores Struggling to get the correct sorting order The current code snippet results in [N/A, N/A, 99%, 90%, ... 20%, 100%, 10%, 0%] being sorted as [0%, 10%, 100%, 20%, ...

use two separate keys for grouping in JavaScript

My current approach involves using the reduce method to organize the data based on the Id of each query. var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descricao: "Creme", }, {Id: "545", valor: "2 ...

What is the method for printing a lengthy output to a file in Python without utilizing "..." in the output text?

I'm currently tackling a text classification challenge using Python. In my attempt to determine the numerical weight of words using TF-IDF, I have developed the following code with a sample dataset: from collections import Counter from tqdm import tqd ...

Emphasize/Style text fields

I am seeking to incorporate a real-time difference viewer into a webpage that maintains whitespace. In the past, I utilized TinyMCE and JQuery in IE6 for a similar project, but it did not preserve whitespace. TinyMCE was not suitable as it is a WYSIWYG ed ...

Issue with using puppeteer for testing applications

Having an issue as a beginner in JavaScript, I'm struggling to solve this error. I am fetching data from a website using puppeteer and trying to verify if it's the correct one: const puppeteer = require('puppeteer'); (async () => { ...

Using Vue to Bring in External JavaScript Files

If I have 2 JavaScript files located in the 'resources/assets/js' directory, named 'app.js' and 'ext_app.js', what could be the issue? Within 'ext_app.js' file, there is a function defined like this: function testF ...

JavaScript - Execute a function when reaching the end of an array

I am currently working on a Node.js program that has a similar structure to the following: var foo = [val,val,val....] var bar = [] for(i=0;i<foo.length;i++){ bar.push(foo[i]) if(bar.length % 29 == 0){ //do something with items 1-29 of bar ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

Automatically refreshing the page when the back button is clicked

Within my ASP.NET application, I have two pages - Page A and Page B. When a user clicks on a link on Page A, they are redirected to Page B. However, if the user then clicks the browser's back button while on Page B, I need to force a refresh of Page A ...