How do I swap two items in an observableArray?

knockout.js

Solution

Here's my version of `moveUp` that does the swap in one step:

moveUp: function(category) {
    var i = categories.indexOf(category);
    if (i >= 1) {
        var array = categories();
        categories.splice(i-1, 2, array[i], array[i-1]);
    }
}

That still doesn't solve the problem, though, because Knockout will still see the swap as a delete and add action. There's an open issue for Knockout to support moving items, though. Update: As of version 2.2.0, Knockout does recognize moved items and the `foreach` binding won't re-render them.

Problem

I have a button that moves an item one position left in an observableArray. I am doing it the following way. However, the drawback is that categories()[index] gets removed from the array, thus discarding whatever DOM manipulation (by jQuery validation in my case) on that node. Is there a way to swap two items without using a temporary variable so as to preserve the DOM node? ``` moveUp: function (category) { var categories = viewModel.categories; var length = categories().length; var index = categories.indexOf(category); var insertIndex = (index + length - 1) % length; categories.splice(index, 1); categories.splice(insertIndex, 0, category); $categories.trigger("create"); } ```

Original source

Related problems