how do i insert element in knockout array at specific index

knockout.js, ko.observablearray

Solution

Use `splice`. The docs aren't real clear on this (I had to double check it myself), but you can use this just like the regular javascript .splice to insert elements as well as remove them. For example:

var vm = {
    array : ko.observableArray(["foo","bar"])
};

ko.applyBindings(vm);

function Add() {
    vm.array.splice(1,0,"ra");    // at index 1 - remove 0 elements and add "ra"
}

Add();   // "ra" gets inserted between "foo" and "bar"

http://jsfiddle.net/aL4D6/

Problem

how do i insert element in knockout array at specific index I understand we have to use slice and push, but what is the best way and how to insert new element at specific position in observable array

Original source

Related problems