Array reducer producing unexpected result of NAN

Query

I am facing an issue with a specific array and reducer function. The array in question is as follows:

let oddsArray = [undefined, undefined, 5, 5]

Accompanied by this reducer function:

const reducer = (accumulator, currentValue) => accumulator + currentValue

Upon calling console.log, I encounter the following output:

console.log(oddsArray.reduce(reducer, 1), 'oddsArray') /// NAN

This only changes when the array excludes any undefined values:

[5, 5, 5, 5] /// 20

Desired Outcome

My objective is to sum up all numbers within the array even if there are undefined elements present. Therefore, the initial total of the array should have been:

let oddsArray = [undefined, undefined, 5, 5] // 10

Is there a method to achieve this?

Thank you!

Answer №1

To handle undefined values, you can use the following code: currentValue || 0

let numsArray = [undefined, undefined, 5, 5]
const total = numsArray.reduce((previousValue, currentValue) =>
                      previousValue + (currentValue || 0), 0);
console.log(total);

Answer №2

For a more versatile solution, particularly when summing only the numbers in an array containing various types of elements, you can utilize Number.isNaN() to determine if the current value of the reducer is a number:

let newArray = [undefined, undefined, 5, 5, null, "hello", {"foo":"bar"}];
const reducer = (acc, currVal) => acc + (isNaN(currVal) ? 0 : currVal);
let result = newArray.reduce(reducer, 0);
console.log(result);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

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

Difficulty encountered when trying to initialize a multidimensional array within a class

Here is a snippet of code that I am currently working on: template<class DT> class AdjMat { protected: DT** myMatrix; int noOfNodes; int noOfEdges; public: AdjMat(int _noOfNodes, int _noOfEdges); //Destructor, constructors and o ...

How to conditionally set the active class in a React component

I am new to using React and I am encountering some issues. My goal is to add an active class when any of these components are opened. I have attempted a solution but it isn't working as expected. I need assistance in adding a background color to the d ...

What exactly is the purpose of calling upon 'express' - a reference to a function or an object?

It is my belief that by utilizing var express = require('express');, the variable express receives a function reference of createApplication(). So, when we invoke express(), it will yield an app object. However, my question is, if var express is ...

Which callback function is best suited for handling the response in an XMLHttpRequest and rendering it on the webpage?

Upon a user action on the page, an AJAX request is made to my Node.js Express server to send data. Here's what happens next: router.post('/', function(req, res){ //user authentication first, then inside that callback res.redirect('/d ...

Order of AngularJS Scope.on and Scope.emit Invocation in a Filter

One of the challenges I am facing involves watching a value in one controller that is changed in another controller within my filters. The goal is to determine whether an emit should be triggered based on the updated value. Here's the current situatio ...

How come the text color isn't changing in my Tailwind CSS and Next.js project?

Having an issue with my Next.js project that uses Tailwind CSS. I've noticed that some colors work while others don't, which is strange. For example: {title ? <div className={`text-2xl mt-2 mb-2 ${title==='Valid Url!' ? 'text ...

Once the image is requested in HTML, three.js makes a subsequent request for the same image

This is a block of code. let image = new THREE.TextureLoader().load("http://odf9m3avc.bkt.clouddn.com/1493817789932.jpg") <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script> <img class='preLoad&apo ...

"Silent Passageway: Connecting Node JS to ASW RDS MySQL Through a Secret

I am currently collaborating on a project with a partner. The backbone of our project is node js, and we are using an AWS RDS MySQL DB for our database. Our main challenge lies in establishing effective communication with the DB through SSH within NodeJS. ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

Utilize the request object from Express within a Mongoose Plugin

I have incorporated an API in ExpressJS along with a middleware that runs before each endpoint controller: app.use(segregationMiddleware); app.get('/some-endpoint', controller1); app.get('/some-endpoint-2', controller2); The segregat ...

What is the best way to pass an array of objects to a component as a prop and then distribute individual objects within the array as props to nested components?

Below this post, I delve into my desired goals and what has almost worked in my endeavors In my application, I have both the <oo-upload> and <oo-uploads> components defined. Essentially, <oo-uploads> showcases a table of <oo-upload> ...

Error in Angular authentication validation when verifying the response of a URL for the status "success"

I've encountered an issue with my code that involves requesting an external URL to check for a successful status: $http.get($scope.linkAnswer).then(function () { linkStatus = true; console.log("veikia") ...

Enhanced Search and Replace Techniques in HTML using jQuery and JavaScript

Although I have some experience with jQuery and Javascript, I am by no means an expert. I have been struggling to find a way to achieve my goal using minimal resources. Maybe you can assist me: This is what I am trying to accomplish: I would like to use ...

Exporting a Three.js scene to a data URL is as easy

After attempting to save an image from a three.js WebGl render, I am encountering an issue where the saved image appears completely blank, despite returning a string of characters: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAK8AAADICAYAAACeY7GXAAADt0lE ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

An error was encountered while parsing JSON: Unexpected token u found at the beginning of the JSON data. This occurred in the file AuthContext.js within the context folder of the src directory

I'm working on a MERN STACK booking app and encountered an error in my code. Can you please assist me with this issue? The error seems to be related to the following part of the AuthContext.js file: const INITIAL_STATE = { user: JSON.parse(localSto ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Unable to retrieve JSON data from the remote URL

I have been attempting to retrieve information from but unfortunately, I am not receiving any data in return. Despite this, I can see the data in my response tab using Google Chrome. My attempts include running it on both a webserver and locally for test ...

Trouble with passing options to ES6 module imports

After coming across this Stackoverflow thread, I am attempting to pass options to ES6 imports. Initially, this code worked without any issues: export default (Param1:any, Param2:any) => { return class Foo { constructor() { cons ...

JSFiddle Functioning Properly, But Documents Are Not Loading

My JSFiddle is functioning properly, but the files on my computer aren't. It seems like there might be an issue with how they are linking up or something that I may have overlooked. I've checked the console for errors, but nothing is popping up. ...