Skip to content

Commit c108006

Browse files
damianitaylorotwell
authored andcommitted
Force sortBy() to maintain original order of items with identical values (#21214)
1 parent 4572938 commit c108006

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

src/Illuminate/Support/Collection.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -1348,7 +1348,7 @@ public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
13481348
// function which we were given. Then, we will sort the returned values and
13491349
// and grab the corresponding values for the sorted keys from this array.
13501350
foreach ($this->items as $key => $value) {
1351-
$results[$key] = $callback($value, $key);
1351+
$results[$key] = [$callback($value, $key), $key];
13521352
}
13531353

13541354
$descending ? arsort($results, $options)

tests/Support/SupportCollectionTest.php

+9
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,15 @@ public function testSortByAlwaysReturnsAssoc()
817817
$this->assertEquals([1 => 'dayle', 0 => 'taylor'], $data->all());
818818
}
819819

820+
public function testSortByMaintainsOriginalOrderOfItemsWithIdenticalValues()
821+
{
822+
$data = new Collection([['name' => 'taylor'], ['name' => 'dayle'], ['name' => 'dayle']]);
823+
$data = $data->sortBy('name');
824+
825+
$this->assertEquals([['name' => 'dayle'], ['name' => 'dayle'], ['name' => 'taylor']], array_values($data->all()));
826+
$this->assertEquals([1, 2, 0], $data->keys()->all());
827+
}
828+
820829
public function testReverse()
821830
{
822831
$data = new Collection(['zaeed', 'alan']);

0 commit comments

Comments
 (0)