Why am I consistently obtaining NaN as the output for the majority of my calculations?

Looking to calculate the average of cities in each state using the Reduce Function in mongoDB, but encountering an issue where only one correct result is obtained while rest return as 'nan'.

Below is the map function:

function map(){
key = {state : this.state};
values = { numberOfCities:1, statePop: this.pop}; 
emit(key, values)}

And the reduce function:

function reduce(key , values){
 numberOfCities = 0.0;
 statePop = 0.0;
 avg = 0.0;
for (i in values){
    numberOfCities += values[i].numberOfCities;
    statePop += values[i].statePop;
    avg = statePop/numberOfCities;
}
return  avg}

The issue lies in returning statePop/numberOfCities leading to nan value, while returning statePop with numberOfCities provides the correct number.

Error Scenario:

Inspecting the json file (a single line from the file):

{ "_id" : "20002", "city" : "WASHINGTON", "loc" : [ -76.990055, 38.902365 ], "pop" : 56756, "state" : "DC" }

Answer №1

i represents the instance of your custom value object, rather than being an index. Therefore, you should use i.property instead of values[I].property.

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

The Power of AngularJS Directives in Harnessing jQuery DOM Event Bindings

I have developed a new directive and have some doubts about the binding syntax like element.bind("click", function(){}). Every time the link function of the directive is called, it creates a duplicate binding. What is the best Angular approach to handle th ...

Can Angular-Material help create a sidenav that toggles on and off?

I am struggling to create a side menu that remains closed by default on all screen sizes and always opens on top of other content. Despite my efforts, it keeps switching at widths over 960px. This is the current code for my menu: <md-sidenav is-locked ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. https://i.sstatic.net/gX9Ij.png One challenge I'm facing is that when the screen attribute ch ...

How do I deactivate dragControls in THREE.JS after enabling them for a group of elements?

My function currently activates dragControls when the "m" key is pressed, but for some reason, it doesn't deactivate when the key is released. How can I go about disabling the dragControls? I attempted to encapsulate the dragControls activation based ...

Attempting to transfer a JSON object from a frontend Form Input to an Express backend

Apologies for bringing up what may seem like a basic issue, but I've been searching extensively (even through axios' documentation) and haven't been able to pinpoint exactly what I need to resolve this issue. I have created a simple To-Do we ...

The :contains method in jQuery functions smoothly in Firefox, Safari, and Chrome, but unfortunately does not work

My code on JSFiddle is having some compatibility issues with the jQuery :contains selector specifically in Internet Explorer versions 7, 8, and 9. The code works fine in Firefox, Safari, and Chrome. You can find the working code here. I tried making the ...

Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below: const messaging = firebase.messaging(); messaging.requestPermission() .then(() =>{ return firebase.messaging().getToken(); }).then(token => { s ...

Angular and Three JS collaboration leads to misplacement of canvas rendering

Currently in the process of developing code for a website, I am attempting to integrate Three JS with Angular. After conducting some research, I have found that this combination is feasible and I have successfully merged these two libraries. However, I am ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Retrieve the element that was clicked by targeting its class name using JavaScript

Unfortunately, I couldn't create this example in JSFiddle as it's currently in read-only mode. My goal is to identify the specific element that was clicked based on a given class. var button = document.getElementsByClassName("mybutton"); button ...

Is there a way to send data to a sibling component without the need to store it as a variable?

In my project, I am utilizing bootstrap vue cards within a v-for loop. Within this loop, one of the tags is supposed to return a value based on the current iteration of v-for. My challenge is that when I save this value as a variable and pass it to another ...

Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

After clicking the submit button, make sure to automatically fill in all empty input fields

I am currently working on a form that includes various input types such as text fields, radio buttons, select dropdowns, and text areas. The form is displayed in a table format with an option to add additional rows. One issue I have encountered is that us ...

Comparing timestamps in JavaScript and PHP - what are the discrepancies?

I seem to be having an issue with the inconsistency in count between two timestamps. Upon page load, I set the input value as follows: $test_start.val(new Date().getTime()); //e.g. equal to 1424157813 Upon submitting the form via ajax, the PHP handler sc ...

Issues occur in React when attempting to load an image using TextureLoader in three.js

I have encountered some difficulties while trying to incorporate three.js into a React project. Despite my efforts, I am unable to successfully load texture images. I have set up my own local server, included a callback method for when loading is finished, ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

Understanding JavaScript Prototypal Inheritance within ES5 Classes

I've been working on creating an XMLHttpRequest interceptor for Angular, encountering a roadblock when trying to intercept a third-party library that uses the XMLHttpRequest API. Although the solution below is functional, I've run into issues wit ...

What is the best way to fulfill promises sequentially?

I'm currently facing a challenge with organizing promises in the correct order. I am developing a chat bot for DiscordApp using Node.js and have extensively searched both on this platform and Google. Despite trying Promise.all and an Async function, I ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...