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
The question asks how to replace "a given index", rather than a given value. The accepted answer works when there are no repetitions in the observableArray, but in case there are repetitions then it will not always behave as expected. E.g. suppose we have:
index = 2;
elements = ko.observableArray([9,8,9]);
and then we use the accepted answer.
elements.replace(elements()[index], 7);
Then elements will be [7,8,9] (because replace uses indexOf, which finds the lowest index of the given value 9), whereas the question surely expects a solution that would make elements be [9,8,7].
To truly replace with newElement the item at index in an observableArray elements, you can use the following.
elements(elements.slice(0, index).concat(newElement, elements.slice(index + 1)));
Something more elegant would be nice. Though IIUC it's a question of readability rather than of performance.