mgiesa
mgiesa

Reputation: 1013

Sort the same observableArray different ways

I have an observableArray of objects that have observable properties. I'd like to display this array twice, each with a different sort order. Is this possible?

I have tried keeping a computed property that gets the array, sorts it and returns it, but this sorts the original array and doesn't do what I want.

function ViewModel(){
    var self = this;
    self.Items = ko.observableArray([]);
    self.ItemsOrdered = ko.computed(function(){
        var i = self.Items();
        return i.sort(function(left,right){
            return 1;
        });
    });
}

See this jsfiddle: http://jsfiddle.net/qhg8t4je/1/ Here I reverse the array, hoping to see the values for A in order in the first list and the values for B in order in the second list, but both lists appear to have been reversed.

I can't find any suggestions for maintaining (or just displaying?) two different sorting orders, I can only find suggestions for maintaining one (as my jsfiddle does).

Upvotes: 0

Views: 62

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191819

.sort updates the original array. Clone the array (e.g. .slice()).

http://jsfiddle.net/qhg8t4je/2/

Upvotes: 2

Related Questions