1

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.