It would be great if the sort filter could be used with arrow functions to tap into PHP's uasort function. It would enable a ton of sorting use cases, such as:
{% set list = [
{ title: 'Apples', quantity: 5 },
{ title: 'Oranges', quantity: 2 },
{ title: 'Grapes', quantity: 4 },
] %}
{% set sorted = list|sort(
(a, b) => a.quantity == b.quantity ? 0 : (a.quantity > b.quantity ? 1 : -1)
) %}
{# `sorted` is now
[
{ title: 'Oranges', quantity: 2 },
{ title: 'Grapes', quantity: 4 },
{ title: 'Apples', quantity: 5 },
] #}
Great idea! Implemented in https://github.com/twigphp/Twig/pull/3132
Even better, I added support for the spaceship operator, so you can now simplify your code to:
{% set sorted = list|sort((a, b) => a.quantity <=> b.quantity) %}
see #3133
Wow, that was quick. Thanks @fabpot, and great idea about the <=> operator!
Most helpful comment
Even better, I added support for the spaceship operator, so you can now simplify your code to:
see #3133