Search code examples
htmlknockout.jshtml-tableknockout-2.0

Add with knockout js items to observable array but show no duplicates on table?


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?


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();
    });