Question

I have an observable array in my knockout js view model that binds to an html table in my view (razor view on MVC).

This table fills with items from another table that have an "add" button, so the user can add as many of the same item to the destination table. My problem is that I want to show in my another table only one for each item...so if the user adds Item1 30 times, the table need to show Item1 - 30 and not 30 times Item1.. but of course the observable array must have those 30 Item1 items.

How can I do that?

Was it helpful?

Solution

Try this code snippet where self.items is your original array with all the items.

self.unique = ko.computed(function() {
    var values = ko.utils.arrayMap(self.items(), function(item){ return item.type})
    return ko.utils.arrayGetDistinctValues(values).sort();
});

OTHER TIPS

Try grouping the array by count like this

function GroupArrayByCount(arr) {
    var a = [],
        b = [],
        prev, result = [];

    arr.sort();
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== prev) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length - 1]++;
        }
        prev = arr[i];
    }
    for (var j = 0; j < a.length; j++) {
        result.push({
            name: a[j],
            count: b[j]
        });
    }
    return result;
}

Now call it in viewModel like this.

self.groupedItems = ko.computed(function(){
    return GroupArrayByCount( self.items());
});

Fiddle: http://jsfiddle.net/codovations/edJwu/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top