The reason you are getting outputs in separate lines, is because you are using IO.inspect
on each element. Instead you should use a single inspect
after accumulating your result in one array!
Try a more Elixir way!
- Instead of using
if
to check if an element is number, use a filter to filter out bad stuff.
- Instead of doing two things in one function, use separate functions.
- Prefer pipelining.
- Do operations after filtering is done, so you have reduced amount of elements to loop through.
- Use LiveBook, for faster debugging of pipeline.
etc.
items = [1, 2, 3, 4, 5, "a"]
items #=> [1, 2, 3, 4, 5, "a"]
|> Enum.filter(fn x -> is_integer(x) end) #=> [1, 2, 3, 4, 5]
|> Enum.with_index() #=> [{1, 0}, {2, 1}, {3, 2}, {4, 3}, {5, 4}]
|> Enum.map(fn {_, i} -> i end) #=> [0, 1, 2, 3, 4]
|> dbg()
Maybe even use stream for bigger list!! (Just replace Enum with Stream) 
items = [1, 2, 3, 4, 5, "a"]
items #=> [1, 2, 3, 4, 5, "a"]
|> Stream.filter(fn x -> is_integer(x) end) #=> [1, 2, 3, 4, 5]
|> Stream.with_index() #=> [{1, 0}, {2, 1}, {3, 2}, {4, 3}, {5, 4}]
|> Stream.map(fn {_, i} -> i end) #=> [0, 1, 2, 3, 4]
|> Enum.to_list()
|> dbg()
If you want original index position, before characters are removed! (As @odix67 pointed out)
items = [1, 'a', 2, 'b', 4, 'c', 35, 'd', 12]
items
|> Enum.with_index()
|> Enum.filter(fn {x, _} -> is_integer(x) end)
|> Enum.map(fn {_, i} -> i end)
|> dbg() # [0, 2, 4, 6, 8]
P.S. Use backtick ```elixir to declare Elixir code while pasting in Forum or GitHub.