carbone icon indicating copy to clipboard operation
carbone copied to clipboard

[Feature Request]: Access nth matching element in an array

Open alxtsg opened this issue 3 years ago • 0 comments

Problem to solve Assume we have the following data:

{
  vehicles: [
    { name: 'Model X', releaseQtr: 1 },
    { name: 'Model Y', releaseQtr: 1 },
    { name: 'Model Z', releaseQtr: 1 },
    { name: 'Truck A', releaseQtr: 2 },
    { name: 'Truck B', releaseQtr: 2 },
    { name: 'Truck C', releaseQtr: 2 }
  ]
}

Using the latest version of Carbone, we can get the first matching element, as mentioned in the document:

Array filters If the filter returns many rows, Carbone keeps only the first occurrence.

If we want to get the first vehicle released in each quarter:

{d.vehicles[releaseQtr=1].name}
{d.vehicles[releaseQtr=2].name}

However, we are unable to get the last matching element. In other words, there are no solutions if we want to get the last vehicle released in each quarter.

Proposed solution I would like to combine array filter and array index to get the nth matching element. For example, in the example above, I would like to be able to do:

{d.vehicles[releaseQtr=1,i=-1].name}
{d.vehicles[releaseQtr=2,i=-1].name}

In other words, if there are multiple matching elements:

  • If i is not specified, keep the first matching one. This makes the proposed feature compatible with existing syntax.
  • If i is specified, get the nth element. One thing to consider is what if the specified index is out of range. For example, if there are only 3 matching elements, what should Carbone do if user specifies i=10? Fall back to keep the first matching element, or throw an error?

When evaluating the filters, Carbone should evaluate in the specified order. i.e. In the example above, Carbone should filter by releaseQtr, and access the last element.

Describe alternatives you've considered Implement a new array formatter to filter and select the nth matching element. For example, arraySelect(releaseQtr=1,i=-1).

Additional context N/A.

alxtsg avatar Jan 24 '22 09:01 alxtsg