How do you replace a given index in an observableArray with another element.
I have:
ViewModel.Elements()[index]
how can i replace it with anot
Like dvijaz correctly points out, the accepted answer replaces a given value. This can cause problems when the given value is not unique in the array.
Instead of slicing the array and then gluing the array back together, I did the following which is more readable IMHO:
ViewModel.Elements()[index] = yourNewElement;
ViewModel.Elements.valueHasMutated();
Thanks to RP Niemeyer for pointing out how .replace works internally.
You can also extend observableArray to support this:
ko.observableArray.fn.replaceIndex = function(index, newValue) {
this.valueWillMutate();
this()[index] = newValue;
this.valueHasMutated();
};
Which means you can do the following:
var arr = ko.observableArray([1, 2, 1, 4]);
arr.replaceIndex(2, 3);
console.log(arr()); // logs [1, 2, 3, 4]