Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js sort list

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>
like image 251
simple Avatar asked May 24 '13 21:05

simple


2 Answers

this.allItems(this.allItems().sort(function(a, b) { return a.name > b.name;}));
like image 130
bert Avatar answered Sep 30 '22 04:09

bert


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)

like image 36
Nowertfy Noodcess Avatar answered Sep 30 '22 03:09

Nowertfy Noodcess