I have below array of objects JSON.
It contains regions value with regCountry with multiple occurrences of both keys.
let arrOfObj = [
{
"regCountry": "Germany",
"region": "Europe"
},
{
"regCountry": "Germany",
"region": "Europe"
},
{
"regCountry": "Spain",
"region": "Europe"
},
{
"regCountry": "Spain",
"region": "Europe"
},
{
"regCountry": "Italy",
"region": "Europe"
},
{
"regCountry": "Austria",
"region": "Europe"
},
{
"regCountry": "India",
"region": "Asia"
},
{
"regCountry": "India",
"region": "Asia"
},
{
"regCountry": "China",
"region": "Asia"
},
{
"regCountry": "Japan",
"region": "Asia"
},
{
"regCountry": "Congo",
"region": "Africa"
},
{
"regCountry": "Egypt",
"region": "Africa"
},
{
"regCountry": "Egypt",
"region": "Africa"
},
]
In above JSON you can see region value is duplicate with country also. I want unique region with list of unique countries under that region. Please check below output need :-
[
{
region: "Europe",
countries: ["Germany", "Spain", "Italy", "Austria"]
},
{
region: "Asia",
countries: ["India", "China", "Japan"]
},
{
region: "Africa",
countries: ["Congo","Egypt"]
}
]
I have tried some ways but it fails. Using .map and .filter but didn’t get proper solution.
Help me to get this solution.
Thanks in Advance.
3
Answers
I have solved this via below method by my own. Thanks for other answers also.
The
reduce
function is used to iterate over thearrOfObj
array and accumulate the result in theacc
variable. The second argument to reduce is a function that takes the accumulator and the current object as parameters.Inside the
reduce
function,acc.find
is used to check if there is already an entry for the current region in the accumulator. If not found, a new region object is created and pushed into the accumulator.The country
obj.regCountry
is then added to the region’s countries array if it’s not already present. The final result is the array of unique regions with their respective lists of unique countries.This uses reduce to build objects containing unique strings, then maps into the structure you want: