Sort the list of goods, order in alphabetical order

I want to sort two lists with items and sort them alphabetically by the first list in the title.

I tried this without any success:

var ViewModel = function() {
    var self = this;

    self.storedProceduresInDB1 = ko.observableArray([{
       Name: "A",
       Id: 1
    }, {
       Name: "C",
       Id: 3
    }, {
       Name: "B",
       Id: 4
    }, {
       Name: "D",
       Id: 2
    }]);

    self.storedProceduresInDB2 = ko.observableArray([{
       Name: "C",
       Id: 3
    }, {
       Name: "E",
       Id: 8
    }, {
       Name: "F",
       Id: 7
    }, {
       Name: "B",
       Id: 4
    }]);

    self.sortLists = function () {
       self.storedProceduresInDB1.sort(function (left, right) {
            return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1);
       });

       self.storedProceduresInDB2.sort(function (left, right) {
            return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1);
       });
    };
}

Jsfiddle

+4
source share
1 answer

In your JSFiddle, the problem is that JavaScript is case sensitive and your code doesn't match its body. Objects in storedProceduresInDB1and storedProceduresInDB2have a key Name, while your sort code is trying to reference Name(note the lowercase N).

Working fiddle with the right cases: http://jsfiddle.net/7zp5K/39/

+3
source

Source: https://habr.com/ru/post/1535397/


All Articles