Sergey Metlov
Sergey Metlov

Reputation: 26301

Keep collection ordered

I have an observable array in my view model. Is it possible to make items be ordered all the time even after pushing additional items?

Example:

[ { a: 4 }, { a: 1 }, { a: 2 } ];

Are displayed on the UI ordered by property a. So [ { a: 1 }, { a: 2 }, { a: 4 } ].
Then I load some new items from the server - [ { a: 5 }, { a: 3 } ], push them into array and the array is still displayed ordered on the UI. Is it possible to do using core ko functional?
Thanks in advance!

Upvotes: 0

Views: 112

Answers (1)

MarcoK
MarcoK

Reputation: 6110

You could call the .sort() method each time data is pushed inside the array - you can't directly insert them in the middle of an array (see documentation).

In your case, you can do the following:

// Todo: insert (push) all inside the observableArray when you retrieved it from the server

// Now sort the data
observableArray.sort(function (left, right) {
    return left.a == right.a ? 0 : (left.a < right.a ? -1 : 1);
});

Upvotes: 1

Related Questions