The output of the sum function in an array is displaying an incorrect value

I have a toggle switch named "Today" and "Yesterday." There is an array of values that needs to be summed based on the selection. Clicking on "Today" should calculate the sum of values for the current day, while clicking on "Yesterday" should add today's and yesterday's values together.

A challenge I am currently facing is outlined below:

public val1;
public val2;
public val3;
public val4;
data = [];

if (value == 'a') {
  val1 = arr.reduce((acc, cur) => acc + Number(cur)); // sum values in the array
} else if (value == 'b') {
  val2 = arr.reduce((acc, cur) => acc + Number(cur));
} else if (value == 'c') {
  val3 = arr.reduce((acc, cur) => acc + Number(cur));
} else if (value == 'd') {
  val4 = arr.reduce((acc, cur) => acc + Number(cur));
}
this.data.push(this.val1, this.val2, this.val3, this.val4);

The issue arises when:

arr = [5, undefined, 5,5] arr = [15,10,25,10]

Upon clicking "Today," it correctly displays [5, undefined, 5,5]. When selecting "Yesterday," it shows [20,10,30,15] (sum of today and yesterday). However, upon clicking on Today again, it displays [5, 10, 5,5], where the value of 10 is carried over from the previous array calculation but not the others. The desired output is [5, undefined, 5,5].

Answer №1

Insert

number1=null;
number2=null;
number3=null;
number4=null;

Prior to the initial if statement, include null instead of undefied

Answer №2

When dealing with JavaScript objects, it is important to remember that they hold a reference to an object. To effectively solve any issues that may arise, it is recommended to assign a value of null before iterating through the process.

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

Guide to include particular data from 2 JSON objects into a freshly created JSON object

I have extracted the frequency of countries appearing in an object (displayed at the bottom). The challenge I am facing is that I require geocode information to associate with country names and their frequencies, so that I can accurately plot the results o ...

Is it necessary to reload the page each time to see updates on the navbar in nextjs?

I recently developed a Next.js application with a Navbar component integrated into my layout.tsx file. The challenge arises when a user logs in and is redirected to the home page, which showcases a link in the Navbar for viewing their profile. However, I n ...

Guide to incorporating the useEffect hook within a React Native View

I am trying to use useEffect within a return statement (inside a Text element nested inside multiple View elements), and my understanding is that I need to use "{...}" syntax to indicate that the code written is actual JavaScript. However, when I implement ...

Unable to include custom matchers for Jasmine in an Angular project with Typescript

My current challenge involves adding multiple new custom matchers to jasmine and utilizing them effectively. I aim to create a file that registers 2 matchers, making all matchers readily available for each test file with just one registration. In this cas ...

What is causing the issue of undefined values when using a hardcoded string for property binding in a component?

I am currently working with a component named "myComponent" which is essentially a drop down button. I want to utilize this component in two different areas of my project - first in the navigation bar and then in the side nav specifically for mobile view. ...

Mistakes found in the code post-building with Angular CLI (ng build)

Hello, I am a beginner in Angular and I am currently trying to set up a new project in Angular using angular/cli. I have followed the steps below to set up an Express server with Angular as the frontend: I first installed angular/cli and then used the com ...

Manipulate data in an array nested inside an object within another array using Mongoose

How do I go about updating the values in an array within an object that is part of another array? { "_id" : ObjectId("63c7ca9584535c160ee4aaed"), "status" : "REJECTED", "steps" : [ { ...

Error with 'Access-Control-Allow-Origin' while making a request using JavaScript

In the process of creating my angular 2 application, I've implemented a module known as github-trend. Within this setup, there is a service that interacts with various functions from the module. scraper.scrapeTrendingRepos("").then(function(repos) { ...

Creating an array and setting its size to the maximum number of elements specified by a

I have been tasked with completing a school assignment that involves writing functions related to employees and their absences. One function is meant to accept the number of employees at a company and return this value to the main program. Another functio ...

Error encountered while utilizing the Extract function to refine a union

I am currently working on refining the return type of my EthereumViewModel.getCoinWithBalance method by utilizing the Extract utility type to extract a portion of my FlatAssetWithBalance union based on the generic type C defined in EthereumViewModel (which ...

Error in Typescript occurrence when combining multiple optional types

This code snippet illustrates a common error: interface Block { id: string; } interface TitleBlock extends Block { data: { text: "hi", icon: "hi-icon" } } interface SubtitleBlock extends Block { data: { text: &qu ...

There is an error message stating: "unable to utilize object of type CI_DB_mysqli_result as an array

When attempting to insert multiple arrays into MySQL, an error is encountered: Error Message: Cannot use object of type CI_DB_mysqli_result as array File Name: operator_pt/Wsmahasiswa.php Line Number: 357 Below is the code snippet from the controller: ...

Error: The element 'scrollable' is not recognized in Angular2

I recently updated my angular2 project to the final release after previously using angular2 RC5 for development. However, I encountered an error message stating "scrollable is not a known element." If I change <scrollable><!--- angular code -- ...

Measuring the Frequency of Letters in a Document

I am trying to analyze the frequency of each letter in an input text file. However, every time I run the program, it ends up displaying the filename instead of the actual letters and crashes. Any suggestions on how to fix this issue? Sample Text File Inpu ...

Is your Express router failing to handle post requests properly?

I've set up my development environment using angular-cli and webpack, with the following configuration in package.json: "dependencies": { "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular ...

Converting a JavaScript string into an array or dictionary

Is there a way to transform the following string: "{u'value': {u'username': u'testeuser', u'status': 1, u'firstName': u'a', u'lastName': u'a', u'gender': u'a&a ...

Declaration error: incompatible data types in initializing a structure array

I've been troubleshooting this issue for some time now, and despite reading similar questions, I'm still unable to identify the mistake in my code. After successfully using malloc to allocate memory for the pointers, I encountered an error (inco ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

Importing data from a text file and storing it in a two-dimensional array

Apologies if my code looks a bit messy, I'm still learning the ropes of programming. My goal is to extract information from a .txt file in the following format: Date-Name-Address and so on. So far, I've been using String.split("-") to divide the ...

When the page is refreshed in Firebase React js, the array data is rewritten

I am facing an issue with adding a list of topics to the firebase database. Each user should be able to create their own unique list of topics, but currently when I refresh the page and try to add another item, the entire list in the database gets erased ...