0

I have a switch button called Today and yesterday. I have an array of values. When I click today it should sum the array values in today and when I click yesterday it should add today and yesterday value and display.

I am facing a problem, that I stated below

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

if (value == 'a') {
  val1 = arr.reduce((acc, cur) => acc + Number(cur)); // add values inside 
  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);

finally

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

When I click today, Its showing [5, undefined, 5,5] which is correct When I click yesterday, Its Showing [20,10,30,15] (today + yesterday) which is correct. When I click today again its showing [5, 10, 5,5] // 10 got append from the previous array but other values don't. My expected o/p is [5, undefined, 5,5].

2 Answers 2

1

Add

val1=null;
val2=null;
val3=null;
val4=null;

before first if, and expect null instead of undefied

Sign up to request clarification or add additional context in comments.

Comments

0

Javascript objects hold a reference to an object, so the best way to solve the problem is to assign null value before iterating the process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.