AniUI Academy
medium+250 XPPractice

Group consecutive runs of equal items

Messaging apps show the avatar once per burst of messages from the same person. Activity feeds collapse five consecutive "edited" events into one row. Both need the list split into runs, where only adjacency counts.

Implement chunkConsecutive(items, keyFn). Walk the array in order, calling keyFn(item) for each item, and start a new group whenever the key differs from the previous item's key. Return an array of those groups, each an array of the original items in order. Keys are compared with Object.is, so NaN matches NaN. keyFn defaults to the identity function. Two equal items that are not adjacent land in separate groups — this is not grouping, it is run-length splitting. An empty input returns an empty array. Never modify the input.

What it has to do

  • Start a new group only when the key changes from the previous item.
  • Put non-adjacent equal values into separate groups.
  • Default keyFn to the identity function.
  • Compare keys with Object.is.
  • Return [] for an empty input, and do not mutate the input.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.