Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an array of objects. Here is my code, and I know there must be a simple mistake that I'm overlooking:

let dataRevenus = [
    { id: 1, label: intl.get("REVENUES_FONCIERS"), value: 230000000 },
    { id: 2, label: intl.get("REVENUES_VALUERS_MOBILIERES"), value: 25000000 },
    { id: 3, label: intl.get("PENSIONS_RETRAITES"), value: 33008.0 }
];

let test = 0;
let sum = dataRevenus
    ? dataRevenus.reduce((acc, item) => {
            console.log("here : " + parseFloat(item.value));

            test = test + parseFloat(item.value);

            return test;
      })
    : 0;

console.log(sum);

My console output shows that the first item is not being included in the calculation. This is the result I get:

here : 25000000
here : 33008
25033008

Despite getting the correct total sum, it seems like I'm missing out on including the value of the first item

Any assistance or advice would be greatly appreciated

Answer №1

you might want to try a different approach with the reduce method, here's a sample code that could work for you:

let dataRevenus = [
    { id: 1, label: intl.get("REVENUES_FONCIERS"), value: 230000000 },
    { id: 2, label: intl.get("REVENUES_VALUERS_MOBILIERES"), value: 25000000 },
    { id: 3, label: intl.get("PENSIONS_RETRAITES"), value: 33008.0 }
];
let sum = dataRevenus
    ? dataRevenus.reduce((acc, item) => {
            console.log("here : " + parseFloat(item.value));
            return acc + item.value;
      }, 0)
    : 0;

console.log(sum);

You might want to consider adding an initializer for the accumulator. Also, as @VLAZ pointed out, be cautious about using external variables in your code.

If you'd like to see this code in action, check it out on jsfiddle: https://jsfiddle.net/5uspgwL8/

An updated version of the original code with the initializer added (and the intl variable): https://jsfiddle.net/weomztad/

For more information, refer to the explanation provided by @Ivar in this link.

Answer №2

The reduce method is a powerful tool for aggregating data in an array using a custom function and an optional initial value:

array.reduce(function(x, y), [initialValue])

When the initial value is not provided (as in your case), the function starts with the first and second elements of the array as arguments. This means that when using item as the second argument in your function, the expression you supplied

test = test + parseFloat(item.value);

will begin with the second element of the array. The beauty of this method is that it automatically passes the total value from one iteration to the next, eliminating the need for an external variable to store the sum.

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

Is styling in React not showing up?

Currently, I am tackling a third-party pagination component in Reactjs. The npm package instructs me to include the line import "rc-pagination/assets/index.css"; in the file. However, despite injecting the index.css into the DOM using the style loader, I ...

Multiple instances of jQuery file being loaded repeatedly

Having an issue with the jQuery file (jquery-1.11.3.min.js) loading multiple times. It seems that other jQuery files in the index.html page might be causing this. Any advice on how to resolve this would be greatly appreciated. <script type="text/javasc ...

Is there a way to access the sqlite3 database file in electron during production?

Currently, I have an electron application that I developed using the create-electron-app package. Inside the public folder of my Electron app, both the main process file and the sqlite3 database are located. During development, I can access the database ...

Effortlessly adjust the top margin of the div element

I have been attempting to smoothly move a div (circle), but I'm facing difficulties. The div instantly jumps to the final position instead of moving smoothly. In an effort to simulate the process of a ball falling, I tried using the animate method wi ...

Is there a way to utilize flex or other CSS properties to wrap element content onto the next line, beginning from the start of its container?

Is there a way to wrap the text content of an element onto the next line, starting from the beginning of its container? I'm looking for something similar to the image provided. Can this be achieved using flexbox or other CSS properties? Here's a ...

Is there a way to retrieve the timestamp of a DOM change event when using MutationObserver for event tracking?

Currently, I am successfully using MutationObserver to monitor changes in the DOM. However, I would like to include a timestamp for each event. Unfortunately, there doesn't seem to be a timestamp property available in the MutationRecord. https://deve ...

converting the names of files in a specific directory to a JavaScript array

Currently working on a local HTML document and trying to navigate through a folder, gathering all the file names and storing them in a JavaScript array Let's say I have a folder named Videos with files like: - VideoA.mp4 - VideoB.mp4 How can I cre ...

Creating combinations of array values while maintaining the integrity of the key-value pairs

Looking for a solution to generate combinations of array values based on key values I have extracted the following data from a file: a string index key and an array of corresponding values SL [1,3] SW [5,7] PL [11,12] PW [16] I aim to create combina ...

Streamlining async/await in for loops using Promise.all: A guide

I'm trying to understand how Promise.all() works in this code. I've learned that you can execute async operations concurrently with Promise.all() for better performance. Currently, the code uses nested for-loops (which is not ideal): type ListGro ...

problem with running a node server on localhost

I've been attempting to test a simple Javascript file, but I'm encountering difficulties. When I try to load the page in my browser, it seems to be stuck loading forever with no warnings. At the bottom of the page, a text bar appears stating "wai ...

Discovering the bottom side of a cube using Euler Angles (or Quaternions) in three.js

Hey there! I have a little puzzle that I could use your help with: Imagine this - I've got a cube that can be rotated around three different axes. I've gathered some data on the cube's rotation, specifically an array of three angles rangi ...

The loading bar animation doesn't begin at a blank slate

I'm currently working on a project that utilizes Django for the backend and Bootstrap for the frontend. I have to admit, I am quite inexperienced when it comes to front-end development; JavaScript seems like magic to me. One of the key features I nee ...

A more efficient method in NumPy for transforming a sequence of characters into a boolean array that represents each individual character in the sequence

Given an array containing strings, the task is to convert each string into a boolean array that corresponds to the alphabet (A-Z). The objective is to achieve this conversion in a vectorized manner without using any loops. For example: Input: A = np.arra ...

How can I dynamically insert a variable string into a link tag using React and TypeScript?

I am just starting out with javascript and typescript, and I need to generate a link based on certain variables. I am currently facing an issue trying to insert that link into <a href="Some Link"> Some Text </a> Both the "Some Text" and "Som ...

Mongoose not functioning correctly when attempting to remove items from an array that meet a certain condition

In my document, I have a property called weeks which is an Array containing Objects. [ { "time": [ "06", "00" ], "active": false, "reason": " ...

Retrieving journal web addresses using the CORE API

I am currently working on pulling journal data from the CORE API in React, specifically focusing on obtaining the title and URL of each journal. My goal is to create clickable links that direct users to the specified URLs. { "identifiers": [ ...

The jQuery keyup event initiates multiple times, increasing exponentially with each trigger

I recently added a search bar with auto-complete functionality to my website. The search bar queries the database for elements that begin with the text entered by the user as they type. Although it works well, I noticed that every time the user inputs ano ...

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

What is the best way to send a prop from a parent component to its child using context in React?

Currently, I am working on fetching data in a React application. My goal is to extract an individual value from the response and pass it as a prop in a context from a parent component. The `trendingData` variable holds information retrieved from an API cal ...

Leveraging the power of ajax to securely save information in a database with the web2py framework

Struggling with a major issue here. I have set up the following tables db.define_table('post', Field('user_email', default=auth.user.email if auth.user_id else None), Field('title', 'strin ...