Immutable.js - is it possible to insert element into list at arbitrary position?

It is worth pointing out that you can also use the insert method which is in fact synonymous with list.splice(index, 0, value) but it feels more intuitive and improves readability greatly.

const myImmutableList = Immutable.fromJS(['foo', 'baz'])
const newList = myImmutableList.insert(1, 'bar')

console.log(newList.toJS()) //["foo", "bar", "baz"]

You are looking for the splicemethod:

Splice returns a new indexed Iterable by replacing a region of this Iterable with new values.

splice(index: number, removeNum: number, ...values: any[])

Where you can specify the index and if you write 0 as removeNum it will just insert the values at the given position:

var list = Immutable.List([1,2,3,4]);
console.log(list.toJS()); //[1, 2, 3, 4]
var inserted = list.splice(2,0,100);
console.log(list.toJS()); //[1, 2, 3, 4]
console.log(inserted.toJS()); //[1, 2, 100, 3, 4] 

Demo JSFiddle.

Tags:

Immutable.Js