Twig: Feature Request: Arrow function support in the Sort filter

Created on 20 Aug 2019  路  3Comments  路  Source: twigphp/Twig

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 },
] #}

Most helpful comment

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

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings