Trying to count the checked items !?


#1

Hello,
I am trying to count the number of checked items in the list created using ionic 2 and TS, i appreciate any help, thanks in advance

html code
<ion-checkbox [checked]="item.checked" (click)="toggleItem(item)" class="checklist-item"></ion-checkbox>
TS code

` toggleItem(item): void {

    this.checklist.toggleItem(item);

}
`


#2

Why not just make the count in for ?


#3

sorry what do you mean? i am a newbie :frowning:


#4

I don’t know if i understand well your question, but look at http://paste.awesom.eu/KRTp


#5

Dear Didelotk, thank you for your support, it is what i need . please look at my code and tell me what i must do else, please …

Thank you in advance.
http://paste.isomorphis.me/sain/QAV&ln


#6

I used the below code and it worked, thank you for your support

 getItemsCount(): number {
        let count= 0;
        this.checklist.items.forEach((item) => {
            if(item.checked){
                count++;
            }
        });
        return count;
    }

#7

Hi,

looks like your checklist is a class instance with methods like toggleItem, renameItem etc. Therefore I’d suggest to implement counting the checked items there.

That being said, it seems checklist also exposes the raw list of items as property. Counting the checked ones seems straightforward then:

var count = this.checklist.items.filter(item => item.checked).length;

I hope I understood your question correctly.

Edit: Ok, I was distracted while writing that, so it took me a while during which you already figured it out :slight_smile:


#8

I would rather use filter instead of a foreach.

Something like that:

var count = this.checklist.items.filter((item) => item.checked).length;

#9

Little change with your code http://paste.awesom.eu/2gLo


#10

if i may ask, why would you rather using filter than forEach ?


#11

cleaner code… and if it exist why not use it? You might see performance issue with large scale arrays. But if its anything around 500 and less filter is the way to go IMO.