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.
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.
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!