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


How do I insert an element at arbitrary position of Immutable.js List?

Best Solution

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.

Related Question