How can we filter an array or dictionary based on an if condition

Hello every one:
Let’s Suppose we have a dictionary:

#let indexed_dates= (
  (0.0, "2023-01-01"),
  (1.0, "2023-01-02"),
  (2.0, "2023-01-03"),
  (3.0, "2023-01-04"),
  (4.0, "2023-01-05"),
  (5.0, "2023-01-06"),
  (7.0, "2023-01-08"),
  (8.0, "2023-01-09"),
  (9.0, "2023-01-10"),
  (10.0, "2023-01-11"))

I want to select just the dates where the index is a multiple of 5,
Can we filter like this ? (I know we can’t because it doesn’t run haha :

 indexed_dates = indexed_dates.map(x=> x if x.at(0)/5==0)

Thank you !

In your example it’s actually an array. You can filter it with filter:

#let indexed_dates= (
  (0.0, "2023-01-01"),
  (1.0, "2023-01-02"),
  (2.0, "2023-01-03"),
  (3.0, "2023-01-04"),
  (4.0, "2023-01-05"),
  (5.0, "2023-01-06"),
  (5.0, "2023-01-07"),
  (7.0, "2023-01-08"),
  (8.0, "2023-01-09"),
  (9.0, "2023-01-10"),
  (10.0, "2023-01-11"))

#indexed_dates.filter(x => calc.rem(x.first(), 5) == 0)

If you had just the dates in the array you could use enumerate:

#let dates = ("2023-01-01", "2023-01-02", "2023-01-03", "2023-01-04", "2023-01-05", "2023-01-06", "2023-01-07", "2023-01-08", "2023-01-09", "2023-01-10", "2023-01-11")

#dates.enumerate().filter(x => calc.rem(x.first(), 5) == 0)

You can also be clever and destructure the index and value in the anonymous function parameter (though I find it less readable in this case):

#dates.enumerate().filter(((i, x)) => calc.rem(i, 5) == 0)

For dictionaries, you can call keys() or values() or pairs() and then call filter() on the result.

2 Likes