How do I insert an element at arbitrary position of Immutable.js
List?
Immutable. js provides many Persistent Immutable data structures including: List , Stack , Map , OrderedMap , Set , OrderedSet and Record .
Immutable. js is a library that supports an immutable data structure. It means that once created data cannot be changed. It makes maintaining immutable data structures easier and more efficient.
Using ImmutableJS can improve dramatically the performance of your application. And, because the immutable data never changes, you can always expect new data to be passed from the above. To make sure you are correctly comparing the data and not updating the UI when there is no change, you should always use the .
Iteration order of a Set is undefined, however is stable. Multiple iterations of the same Set will iterate in the same order. Set values, like Map keys, may be of any type. Equality is determined using Immutable.is , enabling Sets to uniquely include other Immutable collections, custom value types, and NaN.
You are looking for the splice
method:
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With