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

Grouping an array based on a key value returning object not array

I’ve seen many questions on this subject on Stack Overflow, however, they all seem to be returning a single object. (Not what I want)

I have an array below;

const locations = [
    {"city": "London", "district": "Brixton", "id": "Eue3uFjUHKi6wh73QZLX"},
    {"city": "Manchester", "district": "Bury", "id": "QZiiUBgzZaJt2HcahELT"},
    {"city": "London", "district": "Hackney", "id": "v2itdyO4IPXAMhIU8wce"}
]

I would like to map this array into sections based on the "city" key.

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

My expected output is;

 [
    {
       city: "London",
       data: [
          {
             city: "London",
             district: "Brixton",
             id: "Eue3uFjUHKi6wh73QZLX"
          },
          {
             city: "London",
             district: "Hackney",
             id: "v2itdyO4IPXAMhIU8wce"
          }
       ]
    },
    {
       city: "Manchester",
       data: [
          {
             city: "Manchester",
             district: "Bury",
             id: "QZiiUBgzZaJt2HcahELT"
          }
       ]
    }
 ]

I have tried the below;

const groupedLocations = locations.reduce((groups, item) => {
  const { city } = item;
  if (!groups[city]) {
    groups[city] = [];
  }
  groups[city].push(item);
  return groups;
}, {});

However, this returns an object not an array.

>Solution :

Here’s a working code:

const groupedLocations = locations.reduce((groups, item) => {
  const { city } = item;
  
  let relatedGroup = groups.find((group) => group.city === city);
  if (!relatedGroup) {
    relatedGroup = { city, data: [] };
    groups.push(relatedGroup);
  }

  relatedGroup.data.push(item);
  return groups;
}, []);

reduce returns the type of whatever is returned from its reducer function. In your case it was an object, and that’s why you got an object at the end.
I started with an array and each step I looked in the array to find the related group and push the city into that group’s data list.

Hope this helps, good luck!

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