Handling duplicate values in json

I have a result in json, where I need to treat.
can you help me?

[
  %{
    incidentnumber: "9781737",
    ts: "1609252255.121500",
    virtual_params: ":heavy_check_mark: - 9781737 - Normalizado"
  },
  %{
    incidentnumber: "9781906",
    ts: "1609207891.121100",
    virtual_params: ":heavy_check_mark: - 9781906 - Normalizado"
  },
  %{ 
    incidentnumber: "9781737",
    ts: "1609205064.121000",
    virtual_params: ":loading: - 9781737 - Problema"
  },
  %{
    incidentnumber: "9781906",
    ts: "1609204901.120900",
    virtual_params: ":loading: - 9781906 - Problema"
  }
  ]

I need to create a function where it treats as follows.

If there is more than 1 "incidentnumber" with the same name, show only the last one result.

The idea is to look like this example json below.

[
  %{
    incidentnumber: "9781737",
    ts: "1609252255.121500",
    virtual_params: ":heavy_check_mark: - 9781737 - Normalizado"
  },
  %{
    incidentnumber: "9781906",
    ts: "1609207891.121100",
    virtual_params: ":heavy_check_mark: - 9781906 - Normalizado"
  }
  ]

Would have to use Enum.filter with String.contains?
How would it be?

You cannot use Enum.filter here because if an item shall be kept or not is not only dependent on its own content, but also what items came before it. Enum.reduce or for with it’s recent reduce: option can do it.

You can use Enum.reverse/1 followed by Enum.uniq_by/2.

2 Likes

Thanks with Enum.uniq_by, it worked.