I've got a two-dimensional array:
$array = [
['property', 'group1', 'was', 'added'],
['property', 'ouch', 'was', 'removed'],
['property', 'ouch', 'was', 'updated'],
['property', 'group3', 'was', 'added'],
['property', 'group5', 'was', 'removed'],
];
I want to eliminate those subarrays, whose second element (with index 1) coincides with second element of the folowing subarray. In my example above it's ['property', 'ouch', 'was', 'removed'] I want to remove. And I have to solve it using functional programming and without mutations.
So, I wrote this:
function filter($arr)
{
$lineNumber = 0;
$arrayFiltered = array_reduce($arr, function ($acc, $line) use ($arr, &$lineNumber) {
if ((isset($arr[$lineNumber + 1][1])) and ($arr[$lineNumber + 1][1] !== $line[1])) {
$acc[] = $line;
} elseif ($lineNumber === count($arr) - 1) {
$acc[] = $line;
}
$lineNumber++;
return $acc;
}, []);
return $arrayFiltered;
}
The code does its job. But my autotest is not happy: "Should not use of mutating operators" for the lines where we fill our acc and for the line where we increment $lineNumber.
Any advise on how to refactor it to get rid of mutations?