Skip to content

Instantly share code, notes, and snippets.

@mohsenyz
Created December 6, 2020 13:51
Show Gist options
  • Select an option

  • Save mohsenyz/90b81671761df197fadbc1552760e975 to your computer and use it in GitHub Desktop.

Select an option

Save mohsenyz/90b81671761df197fadbc1552760e975 to your computer and use it in GitHub Desktop.
Laravel collection macro for unique consecutive
<?php
Collection::macro('uniqueConsecutive', function ($key = null) {
$lastItem = NULL;
$formatItem = function ($item) use ($key) {
if ($key == null) return $item;
if (isset($item[$key])) return $item[$key];
return optional($item)->$key;
};
return $this->filter(function ($item) use (&$lastItem, $key, $formatItem) {
$itemIndex = $formatItem($item);
if ($lastItem == NULL) {
$lastItem = $itemIndex;
return true;
}
if ($lastItem == $itemIndex) {
$lastItem = $itemIndex;
return false;
}
$lastItem = $itemIndex;
return true;
});
});
<?php
collect([["key" => 1, "value" => 2], ["key" => 1, "value" => 3], ["key" => 2, "value" => 4]])->uniqueConsecutive('key');
// Result : ["key" => 1, "value" => 2], ["key" => 2, "value" => 4]
collect([1, 1, 2, 2, 3, 3, 3, 4, 5, 1])->uniqueConsecutive();
// Result : [1, 2, 3, 4, 5, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment