Cumulo Nimbus
Cumulo Nimbus

Reputation: 9685

Immutable.js .map return multiple elements on one iteration

I am trying to use Immutable's .map() to iterate over a List() of "segments".

Each segment may span multiple days, if so I would like to break this segment up into multiple segments, each which span only one day.

I seem to have the basic logic working:

const segmentedList = nonSegmentedList.map((segment) => {
  if (spansMultipleDays(segment)) {
    return segmentByDay(segment) // returns a list
  } else {
    return segment
  }
})
return segmentedList

My issue is that .map's return will return a List of segments, and populate them in a single segmentedList List item. For example, say segment1 and segment3 span one day, while "segment2" spans three days.

My return value would look something like this:

[
  {segment1},
  [{segment2a}, {segment2b}, {segment2c}],
  {segment3}
]

However, this is what is desired:

[
  {segment1},
  {segment2a},
  {segment2b},
  {segment2c},
  {segment3}
]

Immutable's flatMap function kind of sounds like what I'm looking for, but replacing .map in the above snippet with flatMap yielded the same results.

Upvotes: 1

Views: 193

Answers (1)

Etheryte
Etheryte

Reputation: 25310

One option would be to simply flatten() the collection and then map it.

const collection = Immutable.fromJS([1, 2, [3, 4, 5], 6])
collection.flatten().map(item => console.log(item))
<script src="https://unpkg.com/immutable"></script>

Upvotes: 1

Related Questions