Optimal way to merge two arrays based on a common field?

I have two different arrays in array aggregators with multiple collections that I need to merge efficiently:

  • Array 1: Contains firstname, lastname, and email (10 records).
  • Array 2: Contains age and email (same 10 emails).

I need to combine them into one array with all fields (firstname, lastname, age, email) using email as the key.

For Example:

Array 1:
[{
“firstname”: “A”,
“lastname”: “AA”,
“email”: “A@gmail.com
},
{
“firstname”: “B”,
“lastname”: “BB”,
“email”: “B@gmail.com
},
{
“firstname”: “C”,
“lastname”: “CC”,
“email”: “C@gmail.com
},

]

Array 2:
[{
“age”: “20”,
“email”: “A@gmail com”
},
{
“age”: “21”
“email”: “B@gmail com”
},
{
“age”: “22”
“email”: “C@gmail com”
},

]

Desired Output:
[{
“firstname”: “A”,
“lastname”: “AA”,
“age”: “20”,
“email”: “A@gmail com”
},
{
“firstname”: “B”,
“lastname”: “BB”,
“age”: “21”,
“email”: “B@gmail com”
},
{
“firstname”: “C”,
“lastname”: “CC”,
“age”: “22”,
“email”: “C@gmail com”
},

]

I tried to use iterator but it would cost me as many operations as many emails I have and I wanna know Is there a way to make this efficiently? maybe with built-in Make funcitons?

Thanks in advance!

1 Like

Hey @soso_pkhakadze Welcome to the community!

Here is the easiest and optimal way to combine arrays. To do this, Follow this steps:

  1. Iterate 1 array ideally with more items

  2. Use JSON aggregator with final array or JSON structure with combined items by clicking on Add in Data structure options and then add your sample json in generate option and save the structure. After that create mappings as shown in screenshot with the use of map function.

  3. You can copy and replace items based on your mapping : {{first(map(66.array2; "age"; "email"; 68.email))}}

  1. If needed, you can parse the JSON aggregated and When you run this part again, you will get desired output with combined items

This will help in merging 2 Arrays based on common key as “email”

Best,
@Prem_Patel

1 Like

Thanks a lot! This was exactly what I was looking for!

2 Likes

Glad it helped you! @soso_pkhakadze

Best,
@Prem_Patel