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"
}
]
>Solution :
You coudl group first and then map the citites.
const
data = [{ 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" }],
result = Object
.entries(Object.groupBy(data, ({ state }) => state))
.map(([state, objects]) => ({ state, cities: objects.map(({ cities }) => cities) }));
console.log(result);