cjm2671
cjm2671

Reputation: 19456

Iterating over an array in Elixir

I've got an array of the form:

[
  [~N[2019-02-08 00:00:00.000000], 1],
  [~N[2019-02-02 00:00:00.000000], 8],
  [~N[2019-02-05 00:00:00.000000], 2]
]

Say, for example, I want to convert all the datetimes to_string. What's the best way of doing that?

Upvotes: 0

Views: 172

Answers (1)

BitParser
BitParser

Reputation: 3968

Enum module is the place to look at when you need to work with enumerables. Enum.map takes the enumerable (the list in our case) as its first argument, and the transforming function as its second argument.

[
  [~N[2019-02-08 00:00:00.000000], 1],
  [~N[2019-02-02 00:00:00.000000], 8],
  [~N[2019-02-05 00:00:00.000000], 2]
]
|> Enum.map(fn [dt, num] -> [to_string(dt), num] end)

The result:

[
  ["2019-02-08 00:00:00.000000", 1],
  ["2019-02-02 00:00:00.000000", 8],
  ["2019-02-05 00:00:00.000000", 2]
]

P.S. that is called a list (it's a linked list actually), and not an array.

Upvotes: 2

Related Questions