Mazolo
Mazolo

Reputation: 307

How do I count within conditional foreach binding knockout 3.4.0

I'm binding to an observable array using foreach, I also use If within foreach to test a condition before binding. I want a count of bound elements. $index will not work since it will leave gaps from elements that do not satisfy condition.

I thought of using a function but how do I initialise count to zero.

Upvotes: 0

Views: 283

Answers (1)

kasperoo
kasperoo

Reputation: 1584

You could create a computed that would run through your array, apply some conditions and output the filtered array - then you could normally use $index()

e.g.

this.filteredArray = ko.computed({
    owner: this,
    read: () => {
        let filteredBySomething = ko.utils.arrayFilter(this.testArray(), (item: any) => {
            return item.id === /* some logic here */;
        });
        let result = filteredBySomething ? filteredBySomething : this.testArray();

        return result;
    }
});

Upvotes: 1

Related Questions