javascriptjqueryknockout.jsknockout-2.0knockout-mapping-plugin

Display only distinct values based on property in the markup in Knockout.js


I have this markup:

<div data-bind="foreach: package() ? package().Products() : []">
  <ul data-bind="foreach: Items">
    <li>
      <div>
        <img data-bind="attr: { src: ImageUrl, alt: 'ItemId_' + ItemId }">
      </div>
    </li>
  </ul>
</div>

What I want to achieve (in the markup if possible) is to display only distinct items based on the ItemId, so if there are multiple items with the same ItemId I'll display only one of them.

Is it possible to do that in the markup data-bind property?


Solution

  • There is no straightforward way to filter for unique items in the HTML, and it isn't in keeping with good Knockout programming to put program logic into the HTML. Make a computed that collects the unique items and iterate over the computed.