Error in JavaScript: addition of all numbers not functioning properly within a loop

After attempting to sum all the numeric values within the result[i].quantity array using += or

dataset.quantity = 0 + Number(result[i].quantity);
, I encountered issues where the console.log was returning either NaN or the value from the last iteration like 6135 instead of the expected 36726.

What am I missing in this straightforward code block?

other logic here ], function (err, result) {
        console.log(result); // <<< see №1
        let dataset = [];
        for (let i = 0; i < result.length; i++ ) {
            dataset.min_abs = Math.min(result[i].min_abs);
            dataset.min_1 = Math.min(result[i].min_1);
            dataset.min_200 = Math.min(result[i].min_200);
            dataset.max_1 = Math.max(result[i].max_1);
            dataset.max_200 = Math.max(result[i].max_200);
            dataset.max_abs = Math.max(result[i].max_abs);
            dataset.quantity += Number(result[i].quantity);
            console.log(result[i].quantity) // <<< №2
        }
        console.log(dataset); // <<< №3
    }
);

The result variable (from #1, MongoDB documents) shows:

[ { _id: 1520538161000,
    min_abs: 79500,
    min_1: 80000,
    min_200: 118000,
    avg: 108306.51219512195,
    max_1: 120000,
    max_200: 124493,
    max_abs: 130000,
    quantity: 6993 },
  { _id: 1520536841000,
    ...
    quantity: 5993 },
  { _id: 1520532881000,
    ...
    quantity: 5935 },
  { _id: 1520535521000,
    ...
    quantity: 5735 },
  { _id: 1520534201000,
    ...
    max_abs: 130000,
    quantity: 5935 },
  { _id: 1520531561000,
    ...
    quantity: 6135 } ]

console.log(result[i].quantity) displays the following values:

6993
5993
5935
5735
5935
6135

The dataset variable shows:

[ min_abs: 79500,
  min_1: 80000,
  min_200: 117999,
  max_1: 120000,
  max_200: 124493,
  max_abs: 130000,
  quantity: NaN //or 6135 but not 36726]

Despite trying various approaches, including using .map and .reduce, I still aim to simply sum all the numbers within the array during the current for loop, but have not been successful.

While I understand why I receive 6135 as the result (the last iteration in the loop), I am puzzled as to why += or other constructions are not functioning as expected. This has been a unique challenge for me to tackle.

Answer №1

Consider initializing the dataset with a value of 0 for the "quantity" parameter.

Answer №2

Instead of adding the line:

dataset.quantity += Number(result[i].quantity);
consider replacing it with:
dataset.quantity += result[i].quantity ? 0 : Number(result[i].quantity)

By doing this, you make sure the quantity attribute in the results array is present before adding them up.

Answer №3

additional logic here ], function (err, response) {
        console.log(response); // <<< check here №1
        **let sumTotal= 0;**
        let data = [];
        for (let x = 0; x < response.length; x++ ) {
            data.min_abs = Math.min(response[x].min_abs);
            data.min_1 = Math.min(response[x].min_1);
            data.min_200 = Math.min(response[x].min_200);
            data.max_1 = Math.max(response[x].max_1);
            data.max_200 = Math.max(response[x].max_200);
            data.max_abs = Math.max(response[x].max_abs);
            **sumTotal += Number(response[x].quantity);
            data.quantity  = sumTotal;**
            console.log(response[x].quantity) // <<< №2
        }
        console.log(data); // <<< №3
    }
);

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

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

Unable to retrieve the data from MongoDB

Struggling to retrieve data from MongoDB, my code in the server.js file is not working as expected. You can view the code here. This is the route I'm using in Insomnia for GET requests: here However, when I test it in Insomnia, I receive the followi ...

Vue.js is displaying API data in the browser's console, but it is not appearing on the webpage

I am currently learning about API design and attempting to make an API call that retrieves data from an online API server using the vue.js project through CLI. While I can see the results in the browser console, I'm encountering issues with displaying ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

Is the history object automatically passed to child components within the Router in react-router-dom?

Is it normal for the Router component to automatically pass down the history object to child components? To showcase this concept, consider the following code snippet: App.js ; const App = () => { return ( <> <h1>Hello</h1&g ...

Can a post request be sent in Node/Express using just HTML and server-side JavaScript (Node.js)?

Can a post request be made in Node/Express using only HTML and Server-side Javascript? (HTML) <form action="/submit-test" method="post"> <input type="text" name="id"> <button type="submit">Submit</button> </form> (N ...

How to use jQuery to iterate over changing elements and retrieve their data values

Exploring the potential of a collapsible panel to meet my requirements $(".sport").on("click", function() { var thisId = $(this).attr("id"); var thisChildren = $(this) + ".sportlist"; $(thisChildren).each(function(index) { }); }); <link ...

I am having difficulty with the fadeIn animation not working as expected in my situation

http://jsfiddle.net/9w0v62fa/1/ Instead of using opacity 0 and 1 in two different places, which I find redundant, I attempted to utilize the CSS animate property. However, I couldn't get it to work. Here is my code: .btn{ background:blue; pa ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Node.js Twitter Typeahead.js failing to retrieve suggestions

EXAMPLE CODE FOR TYPEAHEAD : <script type="text/javascript> $('input.typeahead').typeahead({ name: 'Artist', prefetch:{url: '/queryjson, ttl: '1'}, template: '<p><strong>{{firstname} ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

Using Selenium in JavaScript to upload an image is a straightforward process

I am trying to automate the process of uploading a picture using Selenium with the following script: driver.findElement(By.id(`avatar-upload`)).sendKeys(`/home/user/Desktop/smg935-0hero-0930.jpeg`) But I keep receiving this error: ElementNotInteractable ...

I discovered that my Nodejs code is pointing to the Test database instead of my intended database in Mongo db

My insert operation is functioning correctly, moving data from Node.js to MongoDB. However, instead of saving the data in my designated database "School" on my MongoDB cluster, it is getting inserted into a database named "test". How can I direct the inser ...

How can a child class access this.props within a function that overrides a parent class's function?

I am trying to access this.props.childName in the child function, which is defined within the parent function. However, I am encountering a TypeScript compile error (Property 'name' does not exist...). Strangely, if I use this.props.parentName, i ...

For the past 8 hours, my main focus has been on successfully transmitting a basic JSON object containing data from an API from my Express backend to a React component

I have been trying to achieve my initial goal of retrieving data from the API I am using on the backend, inserting that data into my database, and then sending that data through res.json so it can be accessed on the frontend via fetch. Despite all my attem ...

What is the best method to merge three arrays while eliminating any duplicate elements?

I have 3 arrays that I need to merge using names as keys, eliminating any duplicate names and retaining only the highest value based on the sales array. I'm searching for a more efficient solution than multiple foreach loops. [sales] => Array ...

Troubleshooting Challenges with JSON and jQuery Encoding

Having an issue with displaying data from a JSON file using jQuery: { "nombre": "Jesús Ramírez", "edad": "25 Años", "imagen":"file.jpg" } Here's my code: JAVASCRIPT $.getJSON(file.json, function(data) { var name= data.nombre; ...

Extracting the initial data from a JSON stream with jq

What could be the reason behind first(select(.updated_at=="2019-06-03T16:36:53.194Z")) providing more than one result with the given input? {"_id":"a","updated_at":"2019-06-03T16:36:53.194Z"} {"_id":"b","updated_at":"2019-06-03T19:27:15.192Z"} {"_id":"c", ...

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

Expand the div width to the specified measurement horizontally

Is there a way to horizontally collapse a div (container) to a specific width that I can adjust, effectively hiding its content? The collapse effect should move towards the left. <div id="container"> <button type="button" id="myButton"> ...