I had a sorted list using knockout.js for a select list. I want to convert it for an unordered list. What is the method for sorting a list with knockout.js? I am thinking the error is with: allItems().length > 1
http://jsfiddle.net/infatti/Ky5DK/
var BetterListModel = function () {
this.allItems = ko.observableArray([
{ name: 'Denise' },
{ name: 'Charles' },
{ name: 'Bert' }
]); // Initial items
this.sortItems = function() {
this.allItems.sort();
};
};
ko.applyBindings(new BetterListModel());
<button data-bind="click: sortItems, enable: allItems().length > 1">Sort</button>
this.allItems(this.allItems().sort(function(a, b) { return a.name > b.name;}));
var BetterListModel = function () {
this.allItems = ko.observableArray([
{ name: 'Denise' },
{ name: 'Charles' },
{ name: 'Bert' }
]); // Initial items
this.sortItemsAscending = function() {
this.allItems(this.allItems().sort(function(a, b) { return a.name > b.name;}));
};
this.sortItemsDescending = function() {
this.allItems(this.allItems().sort(function(a, b) { return a.name < b.name;}));
};
};
lines explained: weWiliChangeTheArrayToValue(weWilSortTheArrayWithASpecialFunction(ComparatorFunction))
ComparatorFunction ie.
function(a, b) { return a.name < b.name;}
is a special function that helps the sort function to... well sort.
It takes 2 arguments and compares them returning true if first argument is 'bigger' (should be further away on the list) and false if the first argument is 'smaller'
Every (almost) sorting algorithm works by comparing 2 elements of sorted collection until all are in order.
Changing the order is done by making sure that the function returns false when it would return true normally - easiest way to do so is by changing the > operation to <
EDIT one more thing: if you compare non-ASCII characters use return a.localCompare(b); (and return b.localCompare(a);) and when dealing with numbers use "-" sing so it's an arithmetic operation
EDIT2
Warning the above method ">" might break with duplicates in array use
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
instead (or just localCompare)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With