Felix Christo
Felix Christo

Reputation: 229

Sum element is array returning wrong value

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].

Upvotes: 0

Views: 176

Answers (2)

Ankur Jain
Ankur Jain

Reputation: 221

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.

Upvotes: 0

Antoniossss
Antoniossss

Reputation: 32550

Add

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

before first if, and expect null instead of undefied

Upvotes: 1

Related Questions