I have a table of data and I've set up a knockout binding handler that will sort the data of the table when clicking on a . I can sort by the value but the issue is when a group of data is the same value I need the table to then sort that grouping alphabetically by the name column. Here is the knockout (in typescript):
ko.bindingHandlers["sort"] = {
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) => {
var ascending = false;
element.onclick = () => {
var value = valueAccessor();
var array = value.arrayName;
var key = value.key;
ascending = !ascending;
array.sort(function (first, last) {
var left = first;
var right = last;
if (!ascending) {
left = last;
right = first;
}
var keys = key.split('.');
for (var i in keys) {
var keyName = keys[i];
var parentIndex = keyName.indexOf('()');
if (parentIndex > 0) {
keyName = keyName.substring(0, parentIndex);
left = left[keyName]();
right = right[keyName]();
}
else {
left = left[keyName];
right = right[keyName];
}
}
return left == right ? 0 : left < right ? -1 : 1;
});
};
}
};
}
And my table HTML:
<table class="table" id="largeTable">
<thead>
<tr>
<th data-bind="sort: { arrayName: product, key: 'name' }">Name</th>
<th data-bind="sort: { arrayName: product, key: 'type' }">Type</th>
<th data-bind="sort: { arrayName: product, key: 'reviewsNumber()' }">Reviews</th>
<th data-bind="sort: { arrayName: product, key: 'ratingNumber()' }">Ratings</th>
<th data-bind="sort: { arrayName: product, key: 'priceNumber()' }">Price</th>
<th data-bind="sort: { arrayName: product, key: 'date' }">Date</th>
<th data-bind="sort: { arrayName: product, key: 'status' }">Status</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: productOnPage -->
<tr>
<td><div data-bind="text: name"></div></td>
<td><div data-bind="text: type"></div></td>
<td><div data-bind="text: reviews"></div></td>
<td><div data-bind="text: rating"></div></td>
<td><div data-bind="text: price"></div></td>
<td><div data-bind="text: date"></div></td>
<td><div data-bind="text: status"></div></td>
</tr>
<!-- /ko -->
</tbody>
If I have ten products that all have a 4 star rating then I would want the table to sort those ten by the name attribute. How can I do this?