cowboy192
cowboy192

Reputation: 85

Calculation in angular observable subscription delivers wrong data

I have a observable which delivers data in the following structure:

export interface expResults {
  user: User;
  results: {
    experiment: Experiment
    attempts: number
    passed: boolean
  }[];
}

What I want to do now is to calculate the rate of experiments performed at least once. For example:

  Donald;
  results: {
    experiment: Experiment1
    attempts: 3
    passed: true
  }[];

  Micky;
  results: {
    experiment: Experiment1
    attempts: 0
    passed: false
  }[];

  Frank;
  results: {
    experiment: Experiment1
    attempts: 3
    passed: false
  }[];

  Lisa;
  results: {
    experiment: Experiment1
    attempts: 0
    passed: false
  }[];

In this case I expect the output "0,5" because 50% of the users tried the experiment at least once.

I use the following code but it returns no data. Can someone see my mistake?

expResults: Observable<expResults[]> = of();
ngOnInit(): void {
this.expResults = this.dataService.getData(topic);
this.expResults.pipe(map((resultSet2) => {
            return resultSet2.reduce((acc, resultSet) => {
              resultSet.results.forEach((t) => {
                if (acc[t.attempts] == null) acc[t.attempts] = [];
                else {
                  if (t.attempts == 0) {
                    acc[t.attempts].push(0);
                  } else {
                    acc[t.attempts].push(1);
                  }
                }});
              return acc;
            }, {});
          }),
          map((resultsObj) => {
            return Object.keys(resultsObj).map((key) => {
              const count = resultsObj[key].length;
              const sum = resultsObj[key].reduce((a, b) => a + b, 0);
              const rate = sum / count;
              this.ChartData[0].data.push(Number(rate));
            });
          })
        )
          .subscribe();
}

Upvotes: 0

Views: 263

Answers (1)

munleashed
munleashed

Reputation: 1685

this.expResults.pipe(map((result: expResults[]) => {

  // Calculate number of experiments performed at least once
  const numberOfPerformed = result.reduce((acc, item) => {
    // If attempts > 0 then add 1 to the sum
    acc += (item.results.attempts ? 1 : 0);
    return acc;
  }, 0)

  // Calculate rate
  return numberOfPerformed / result.length;

})).subscribe((rate) => {
  // rate
})

Upvotes: 2

Related Questions