AniUI Academy

Group consecutive runs of equal items

mediumArrays & Objects+250 XPPractice

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.

Arguments

itemsArray
The input list to split into runs.
keyFn(item) => any
Called with each item to derive the key used to detect run boundaries. Defaults to the identity function.

Returns

Array<Array> — An array of groups. A new group starts every time the key changes from the previous item's key.

Examples

chunkConsecutive([1, 1, 2, 2, 2, 3]);
// [[1, 1], [2, 2, 2], [3]]
chunkConsecutive([1, 2, 1]);
// [[1], [2], [1]] — non-adjacent duplicates stay apart

chunkConsecutive(
  [{ t: "a" }, { t: "a" }, { t: "b" }],
  (item) => item.t,
);
// [[{ t: "a" }, { t: "a" }], [{ t: "b" }]]

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.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.