Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

push to array index and reduce index having same key

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading