Created
December 6, 2020 13:51
-
-
Save mohsenyz/90b81671761df197fadbc1552760e975 to your computer and use it in GitHub Desktop.
Laravel collection macro for unique consecutive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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