Please help me merge array’s cities whereas the state is same and remove duplicate index. The expecting output is given below
Input array
[
{
"state": "delhi",
"cities": "central delhi"
},
{
"state": "jharkhand",
"cities": "dumka"
},
{
"state": "jharkhand",
"cities": "deoghar"
},
{
"state": "jharkhand",
"cities": "jasidih"
},
{
"state": "karnataka",
"cities": "bail hongal"
},
{
"state": "ladakh",
"cities": "kargil"
}
]
I have tried multiple code but adding this one as i am still trying to get my desired output
arr1.map((row, index) => ({
itemLabel: arr1.state,
itemValue: arr1.cities - arr2[index].cities
}))
Need this output
[
{
"state": "delhi",
"cities": "central delhi"
},
{
"state": "jharkhand",
"cities": ["dumka","deoghar","jasidih"]
},
{
"state": "karnataka",
"cities": "bail hongal"
},
{
"state": "ladakh",
"cities": "kargil"
}
]
4
Answers
You can first use
Object.groupBy
to group all objects with the samestate
, then transform the result by mapping over its entries.You could group first and then map the cities.
This can be done by grouping the cities by state and merging the cities for states that appear multiple times,This can be done using JS reduce .