Search code examples
filtervega-lite

How to filter string prefixes with Vega-lite


Is it possible to filter records with Vega-lite by strings?

Example:

  1. record: "ABCD"
  2. record: "AMFK"
  3. record: "AMRK"

I would like to process only records where the string starts with "AM".

I studied the documentation and found solutions only for comparing the entire string. Is it possible to truncate the string? Or use something like "LEFT()" in Excel? Or something completely different?

Edit: Possibly of importance, I'm using the Vega-lite app in Airtable.


Solution

  • You can do this using a filter transform along with an appropriate vega expression. For example (open in editor):

    {
      "data": {
        "values": [
          {"key": "ABCD", "value": 1},
          {"key": "AMFK", "value": 2},
          {"key": "AMRK", "value": 3}
        ]
      },
      "transform": [{"filter": "slice(datum.key, 0, 2) == 'AM'"}],
      "mark": "bar",
      "encoding": {
        "x": {"type": "quantitative", "field": "value"},
        "y": {"type": "nominal", "field": "key"}
      }
    }
    

    enter image description here