Search code examples
javascriptreactjsimmutable.js

How to get next element in Immutable List when use .map?


i have 1 immutable List like this

const list = new List([
new Map({ title: 'first', complete: true }),
new Map({ title: 'second',complete: false }),
])

when i use

list.map((value,index) => {
//HOW TO GET VALUE OF NEXT ELEMENT IN HERE ?
})

Solution

  • You can do it like this

    list.map((value,index) => {
      const next = list.get(index + 1);
      // next will be undefined when the value is last one in the list (and index + 1) is out of bounds because of that
    })
    

    Just for clarification this example is using the fact that Immutable List is descendant of Collection.Indexed which has get(index) method