3
votes

I'm trying to populate an unordered list using the LastNames from my viewModel.Names. It populates fine but I only want distinct values and this is currently giving multiple of the same LastName? How can I get the distinct values?

Update: there is a FirstName MiddleName LastName

View Model:

<ul data-bind="foreach: viewModel.Names">
    <li><a data-bind="text: LastName"></a></li>
</ul>

Update: I can get the distinct values with the following function, I cannot data-bind the text though. Here is a screenshot of my console.log of my array of cities which is in the same situation as LastName.

enter image description here

this.LastNames = ko.dependentObservable(function () {
    var data = ko.utils.arrayMap(viewModel.Names(), function (item) {
        return item.LastName()
    })
    return ko.utils.arrayGetDistinctValues(data).sort();
});

Here is my new View Model:

<uldata-bind="foreach: LastNames">
    <li><input type="checkbox"/><a data-bind="text: []"></a></li>
</ul>
1

1 Answers

2
votes

If I understood right, what you need is to create a computed array like this :

// this beeing your model
this.distinctNames = ko.computed(function(){
   var distinct = [];
   for (var i = 0; i < this.Names.length;i++) {
       if (distinct.indexOf(this.Names[i]) == -1)
          distinct.push({LastName:this.Names[i]});
   }
   return distinct;
}, this);

With this computed array, using in your view the distinctNames variable will give you a filtered array based on the current state of Names array.

Your foreach will then be :

<ul data-bind="foreach: viewModel.distinctNames">
    <li><a data-bind="text: LastName"></a></li>
</ul>

See http://knockoutjs.com/documentation/computedObservables.html

EDIT

You access foreach's data the wrong way. You should use $data which referes to the current foreach value :

<ul data-bind="foreach: LastNames">
    <li><input type="checkbox"/><a data-bind="text: $data"></a></li>
</ul>