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.
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
keyFnto 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.
- 1.splits a sorted list into runs
- 2.uses the key function to decide sameness
- 3.keeps non-adjacent equal values apart
- 4.returns an empty array for empty input
- 5.wraps a single item in one group
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.