Select a collection in 2 columns
4 answers
You can use the slice array method to create two collections:
<div data-bind="foreach: list.slice(0, list.length / 2) "> <span data-bind="text: $data" /> </div> <div data-bind="foreach: list.slice(list.length / 2)"> <span data-bind="text: $data" /> </div> If you have an observable array, you need to change the bindings a bit:
<div data-bind="foreach: list.slice(0,list().length / 2) "> <span data-bind="text: $data"/> </div> <div data-bind="foreach: list.slice(list().length / 2)"> <span data-bind="text: $data"/> </div> JSFiddle demo.
+11
A safe and clean example of using an observable array
<!-- ko with: myObservableArray --> <div data-bind="foreach: $data.slice(0, $data.length / 2)"> <span data-bind="text: $data"/> </div> <div data-bind="foreach: $data.slice($data.length / 2)"> <span data-bind="text: $data"/> </div> <!-- /ko --> +2
You can simply use mod 2, for example:
<div data-bind="foreach: list"> <!--ko if: $index() % 2 == 0 --> <div class="row"> <div class="col-md-6"> <span data-bind="text: $data"></span> </div> <div data-bind="with: $parent.list()[$index()+1]" class="col-md-6"> <span data-bind="text: $data"></span> </div> </div> <!--/ko--> </div> 0
Just create an external table with one row and two cells. Inside the first cell, another table with only even indices is placed. In the second cell, it is associated with odd indices.
<table style="table-layout:fixed;"> <tr> <td> <table style="table-layout:fixed;"> <tbody data-bind="foreach: someObservableArray"> <!--ko if: $index() % 2 == 0 --> <tr> <td data-bind="text: somePropertyInArrayObject"></td> </tr> <!--/ko--> </tbody> </table> </td> <td> <table style="table-layout:fixed;"> <tbody data-bind="foreach: someObservableArray"> <!--ko ifnot: $index() % 2 == 0 --> <tr> <td data-bind="text: somePropertyInArrayObject"></td> </tr> <!--/ko--> </tbody> </table> </td> </tr> </table> 0