0

I have a computed array like this,

self.weapons = ko.observableArray(
  []
  );

self.wings = ko.observableArray(
  []
  );


 self.itemList = ko.computed( function()
 {
     return self.weapons().concat(self.wings());
 }
 },
 this );

i would like to sort this array.

i can sort ko.observableArray with no problem.

issue here is i think, ko.computed is computes back again after the sorting is done.

also: is there a better way concatenating multiple observableArrays together?

Thank you.

1 Answer 1

2

Just sort the concatenated array.

self.itemList = ko.computed(function () {
    var weapons = self.weapons(),
        wings = self.wings();
    return weapons.concat(wings).sort();
});

It will have to be resorted every time either array changes but there's not much you can do about that.

If you are going to make many changes in succession, consider using the rateLimit extender (or throttle prior to knockout 3.1.x) on your computed observable. This will limit the amount of times notifications are sent out by the observable by collapsing all notifications made within a certain time period.

self.itemList = ko.computed(function () {
    ...
}).extend({ rateLimit: 500 }); // wait at least 500ms before first notification
Sign up to request clarification or add additional context in comments.

8 Comments

thank you. this works of course, but it is extremely slow. adding 100 items essentially means 100^2*log100. ideally concatenation would be shallow, and sort only needed when list is complete. forget the shallow merge, is it possible to sort this array only when i want it. like after adding 100 elements, instead of every push.
Will you be modifying the arrays in quick succession or will it change over long periods of time? Would you rather have it throttled sorting (so you can add many quickly but will sort after it stops changing for a while) or do you want it sorted on demand? I'm sure that would be possible to write up, I'll just need to know what your goal is for it.
just want suppress sorting when i add many items in succession.
In that case, you can throttle your arrays so it doesn't get updated too frequently.
it was that easy huh. i reduced iteration count from 100 to 1. brilliant! thank you
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.