JSFiddle - React, Tailwind, and code Playground
by Gabriel Tran
HTML
<button data-bind="click: calculateRows">Go</button>
<table class="footable table-striped" data-bind="foreach: rows">
<tr style="width: 33%" data-bind="foreach: $data">
<td data-bind="text : Name"></td>
</tr>
</table>
JavaScript
Array.prototype.transpose = function () {
var array = this;
return array[0].map(function (col, i) {
return array.map(function (row) {
return row[i] ? row[i] : new SubModel();
});
});
}
var SubModel = function (name) {
this.Name = ko.observable(name);
}
var ViewModel = function () {
var self = this;
this.options = ko.observableArray([new SubModel('AC'), new SubModel('BA'), new SubModel('CA'), new SubModel('AB'), new SubModel('BB'), new SubModel('BC'), new SubModel('AA')]);
this.rows = ko.observableArray();
this.columnLength = ko.observable(3);
this.calculateRows = function () {
var result = [],
temp = [],
row, colLength = parseInt(self.columnLength(), 10),
options = self.options().sort(function (l, r) {
return l.Name() > r.Name() ? 1 : -1
});
for (var i = 0, j = options.length; i < j; i++) {
if (i % colLength === 0) {
if (row) {
temp.push(row);
}
row = [];
}
row.push(options[i]);
}
//push the final row
if (row) {
temp.push(row);
}
//flip it
result = temp.transpose();
//return result;
self.rows(result);
};
}
ko.applyBindings(new ViewModel());