Reputation: 651
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below
<div>Progress : 2{{count}}</div><div>completed : 2{{count}}</div>
declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
arrayVal:any;
currentVal : any;
title = 'projectchart';
public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
ngOnInit(){
let count=0;
this.array.forEach((item, index) => {
console.log(item.progress) ;
count +=item.progress ;
});
console.log(count);
}
}
Upvotes: 0
Views: 1647
Reputation: 56
You can use library like underscore, where a function like countBy will do what you want.
In your case:
_.countBy(array, (item) => item.progress === 100 ? 'completed' : 'progress');
the result will be:
{completed: 2, progress: 2}
Upvotes: 0
Reputation: 22213
Try like this:
progressCount:number = 0;
completedCount:number = 0;
ngOnInit() {
this.array.forEach(item => {
if (item.progress < 100) {
this.progressCount ++;
} else {
this.completedCount ++;
}
});
}
HTML:
<div>Progress : 2{{progressCount}}</div><div>completed : 2{{completedCount}}</div>
Upvotes: 1
Reputation: 2881
Actually, You are adding the progress value in count. Please try this..
ngOnInit(){
let progress_count=0;
let completed_count=0;
this.array.forEach((item, index) => {
if (item.progress == 100) {
progress_count++;
} else {
completed_count++;
}
});
console.log('Progress count :',progress_count);
console.log('Completed count :',completed_count);
}
And use progress_count and completed_count in your HTML
Upvotes: 0
Reputation: 163
Change this line
count +=item.progress;
To
if (item.progress === 100) {count += 1;}
Upvotes: 1