Sum of a particular value in list of maps

I have a list of maps

[
  %{
    "name" => "Gobi Manchurian",
    "no_of_servings" => 2,
    "spiciness" => 1,
    "total_dish_price" => 55
  },
  %{
    "name" => "Gobi Manchurian",
    "no_of_servings" => 2,
    "spiciness" => 1,
    "total_dish_price" => 55
  }
]

from the above I need all “total_dish_price” as list, when i tried this

new_map = Enum.map(price_map_list, fn (x) -> x["total_dish_price"] end)

I am getting this output ‘77’

Can someone help me out

You get a list back with the distinct values 55 each. 55 is ASCII for the digit 7.

So you get them inspected as a charlist.

Try i '77' in iex, which will tell you why [55, 55] === '77'

4 Likes
iex(1)> [55, 55]
'77'

That’s because that is what it is. :slight_smile:

Remember that character lists (lists of integers of values in the unicode range) get printed as character strings, but they are still lists, you are only seeing it that way because of how it is printed. Try i '77' in IEX to see details (you can do that to any value).

EDIT: @Nobbz was slightly faster! Lol

4 Likes

@OvermindDL1 Thanks guys. and yep. when I printed [55,55] in iex i got ‘77’ so in my application I just directly sent my value to the relevant field and I am getting [55,55] in the result set :slight_smile:

2 Likes

Here’s a bit more detail, for novices like me. :slight_smile:

More details on why Elixir behaves this way can be found in the Charlists section of List's documentation:

https://hexdocs.pm/elixir/List.html#module-charlists

And if you really want to see [55, 55] in your terminal output then you can pass charlists: :as_lists to inspect and IO.inspect, e.g.:

iex(7)> [55, 55]
'77'
iex(8)> inspect([55, 55])                      
"'77'"
iex(9)> inspect([55, 55], charlists: :as_lists)
"[55, 55]"
3 Likes