Values are being subtracted correctly without displaying any negative results

I'm working with the following code snippet:

const my_transactions = [{amount: -100,currency: 'EUR'},{amount: -200,currency: 'EUR'},{amount: -400,currency: 'EUR'}];
let total = 0;
my_transactions.forEach(el => total = total - el.amount);
console.log('total:',total);

All the amounts are negative in this code. The goal is to sum all the amounts and display the overall balance. In this scenario, the balance is negative. The expected output should be

-700

However, the variable "total" ends up with a positive value instead. What could be causing this unexpected behavior?

Answer №1

Subtracting a negative value is essentially the same as adding a positive value.

These calculations will yield the same outcome:

console.log('subtracting:', 0 - (-100));
console.log('adding:', 0 + (+100));

If your goal is to accumulate all these negative numbers to reach a total of -700, then opt to add them together instead of subtracting:

my_transactions.forEach(el => total = total + el.amount);

Answer №2

To switch from subtraction to addition, replace the minus (-) operator with the plus (+) operator.

Remember that subtracting a negative number is equivalent to adding a positive number.

const my_sales = [
  { amount: -100, currency: 'EUR' },
  { amount: -200, currency: 'EUR' },
  { amount: -400, currency: 'EUR' }
];

let total = 0;
my_sales.forEach(item => total = total + item.amount); // Change - to +

console.log('Total sales:', total);

An alternative and more efficient method is to use the reduce function:

const mySales = [
  { amount: -100, currency: 'EUR' },
  { amount: -200, currency: 'EUR' },
  { amount: -400, currency: 'EUR' }
];

let total = mySales.reduce((sum, { amount }) => sum + amount, 0);

console.log('Total sales:', total);

Answer №3

This is an addition, not subtraction

const my_transactions = 
  [{amount: -100,currency: 'EUR'},
   {amount: -200,currency: 'EUR'},
   {amount: -400,currency: 'EUR'}];
   
let total = 0;

my_transactions.forEach(el => total += el.amount);

console.log('total:', total);

For a more concise code:

const my_transactions = 
  [ { amount: -100, currency: 'EUR' }
  , { amount: -200, currency: 'EUR' }
  , { amount: -400, currency: 'EUR' }
  ];
let total = my_transactions.reduce((s,{amount:v}) => s + v, 0);

console.log('total:', 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

Experiencing trouble with the integration of react native Vector icons in a current project

I'm encountering an issue with React Native Vector Icons. The error message I'm receiving says: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You l ...

Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan. Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly. For instance, if someone submits August 21 and 200, I w ...

A method for assigning a single event listener to multiple events in a React component

I find myself in a situation where I have two events, onClick and onSelect, both of which share the same event handler. I am wondering what the most efficient way to handle this scenario would be - should I create a common method and then call the event ...

Java persistence with AJAX technology

Being a beginner in server side development, I am currently working on creating a database application for my company that will store links to all our marketing videos. Each entry consists of a URL (link to video), description, industry, and more. So far, ...

The only thing visible on my project is the homepage, void of any buttons or additional pages

After completing this school project, I believed that everything was done correctly. However, as I faced issues with the code, I decided to seek help and share my app.js and bin section for clarification. Starting it with npm on the localhost as shown in ...

Retrieve targeted information from MySql using jQuery AJAX Success

I've got this AJAX code set up to retrieve data from MySQL and display it in the Success block. $.ajax({ type:"POST", url:"index.php", success: function(data){ alert(data); } }); This is my Query $sql ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

The HTTP request arrives with no content within the body

I am in the process of developing a basic client-server application using Node and Express. The goal is for the program to receive a JSON input on the client-side, perform some operations, and then send data to the server-side. Currently, I am able to sen ...

Having trouble establishing a new local Windows directory structure with Selenium

After following the guidelines provided here and here, I am striving to ensure that the directory where my results reports are stored is consistently available for each user. new File(sampleFolder).mkdir(); The sampleFolder path displayed in the Eclipse ...

Utilize esbuild to load Bootstrap JavaScript libraries

I have been attempting to incorporate the bootstrap JS into my esbuild setup: // index.js import 'jquery-import' import 'bootstrap' // jquery-import.js import jquery from 'jquery' window.jQuery = window.$ = jquery; The build ...

Displaying a certain div when clicked within a loop using Vue.js and Laravel

I am currently facing an issue with displaying a hidden div upon click. The problem arises when using a loop to dynamically generate all the divs. Whenever I click the button, it shows all the divs instead of just one specific div on each click. I attempte ...

Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or ...

Combining multer, CSRF protection, and express-validator in a Node.js environment

Within my node.js application, I am utilizing an ejs form that consists of text input fields in need of validation by express-validator, an image file managed by multer, and a hidden input housing a CSRF token (a token present in all other forms within the ...

"Uh-oh! Encountered a new unexpected runtime error. Can't seem

While working on my portfolio in Next.js, I encountered an issue. I added a header to display on all pages by placing it in _app.js without making any changes to _document.js. Here is the error message: Unhandled Runtime Error Error: No router instance fo ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

Determine the number of elements located inside a designated slot

Take a look at this Vue component code: <template> <!-- Carousel --> <div class="carousel-container"> <div ref="carousel" class="carousel> <slot></slot> </div> </div&g ...

Inject fresh variable values into the serialization process

Within my login form, I have fields for Username and Password. Upon clicking the login button, a Javascript function is triggered to make an ajax request to the login controller. To serialize the form data, I used the code snippet below: var parameters = ...

What steps are involved in extracting post data from the javascript DOM using php?

Having an issue where my JavaScript sends data to PHP, but the parsing in PHP keeps failing. The data is received by PHP and displayed in a text area, however, it needs proper formatting before being parsed. Can anyone advise on how to correctly format the ...

I am looking to save the data entered in an HTML form directly into a JSON file within the webpage

I am currently storing the value in an array on the server, but I would like to store it only on the client side within the webpage. I want to write the form data from the HTML form into a JSON file that remains on the page itself and is not sent to the ...

The input value remains a string even after it has been converted to a float

I can't figure out where I'm going wrong. I'm attempting a simple task: getting user input, converting it to a float, and performing a calculation with that value. However, all I keep getting is NaN. Here's the input (I normally replac ...