Most efficient way to remove duplicates in an array of CDT or Map based on a specific key?

I need to check a specific field in an array of cdt or map for duplicates, and return an array of cdt or map without duplicates on that field. For example:

CDT Array:

{
type!example(

email: "hello@gmail.com",

type: 1,

date: 01/01/2022

),

type!example(

email: "hello11@gmail.com",

type: 1,

date: 03/02/2023

),

type!example(

email: "hello@gmail.com",

type: 2,

date: 01/02/2023

)

}

In the above case, I want to return an array with unique email fields. Since the first and third item in the array have the same email address "hello@gmail.com", I only want to return the first one.

  Discussion posts and replies are publicly visible

Parents Reply
  • +1
    Certified Lead Developer
    in reply to walkers

    Hi,
    Following Stefan's suggestion, I have employed the 'unique' function and 'forEach' loop to retrieve the CDTs. Please refer to the code snippet below:

    a!localVariables(
      local!testData: {
        {
          email: "hello@gmail.com",
          type: 1,
          date: today()
        },
        {
          email: "hello11@gmail.com",
          type: 1,
          date: today()
        },
        {
          email: "hello@gmail.com",
          type: 2,
          date: today()
        }
      },
      local!uniqueEmails: union(
        touniformstring(local!testData.email),
        touniformstring({})
      ),
      a!forEach(
        items: local!uniqueEmails,
        expression: index(
          index(
            local!testData,
            wherecontains(
              tostring(fv!item),
              touniformstring(index(local!testData, "email", {}))
            ),
            {}
          ),
          1,
          {}
        )
      )
    )

Children