Group_adjacent

Takes an array and groups it into multiple arrays based on &groupExpression value match.

Syntax

array group_adjacent(array $entry, &groupExpression)

Groups $entry, outputting multiple arrays based on adjacency and expression match.

Parameters

$entry: The array to group.
&groupExpression: The value to group by if adjacent items match.

Example

{
    "array": [
        { "key": "a" },
        { "key": "b" },
        { "key": "b" },
        { "key": "a" },
    ]
}
{
    GroupedArray: group_adjacent(array, &key)
}
{
    "GroupedArray": [
        [
            { "key": "a" }
        ],
        [
            { "key": "b" },
            { "key": "b" }
        ],
        [
            { "key": "a" }
        ]
    ]
}

In this example, the array input is grouped by the “key” value. This yields an array of three arrays.

The first array contains a single object as there are no adjacent objects in the input array that match the key value.

The second array contains two objects as there are two adjacent objects in the input array that share the key value “b”.

The third array again contains a single object as, even though there are two keys in the input array that share the key value “a”, they are not adjacent.

Notes

Synergy with sort_by function

In order to group all matching keys in an array, group_adjacent can be used on an already sorted array.

Expanding on above example, the following transformation will yield an output of arrays that groups all keys in the input array, because adjacency is ensured by the sort_by function.

{
    GroupedArray: group_adjacent(sort_by(array, &key), &key)
}
{
    "GroupedArray": [
        [
            { "key": "a" },
            { "key": "a" }
        ],
        [
            { "key": "b" },
            { "key": "b" }
        ]
    ]
}