Blog of Raivo Laanemets

Stories about web development, freelancing and personal computers.

Group array by adjacent elements in JavaScript


Recently I needed to group some log lines by date difference: all log lines apart less than one hour go into one group. I did not find any JavaScript library for this (it's not in underscore/lodash) and I had to made my own.

The following code is based on this StackOverflow answer. The original code only considers item equality. I generalized it by supporting a custom callback that compares the previous and current items.

function groupAdjacent(array, cb) {
    return array.reduce(function(prev, cur) {
        if (prev.length > 0) {
            var group = prev[prev.length - 1];
            var last = group[group.length - 1];
            if (cb(last, cur)) {
                // Split, create a new group.
                prev.push([cur]);
            } else {
                // Put into the current group.
                group.push(cur);
            }
        } else {
            // The first group.
            prev.push([cur]);
        }
        return prev;
    }, []);
}

The function has to be supplied the array and the callback that compares adjacent element pairs. Example call:

groupAdjacent([1, 2, 3, 6, 7, 8], function(prev, cur) { return cur-prev > 1 })

This will split array where the difference between adjacent elements is creater than 1. This call will output:

[[1, 2, 3], [6, 7, 8]]

Fiddle: https://jsfiddle.net/57hyxghb/2/


Comments

No comments have been added so far.

Email is not displayed anywhere.
URLs (max 3) starting with http:// or https:// can be used. Use @Name to mention someone.