I have an array as shown below.
I want this pattern:
I want to Get distinct "CityRef" and "City". then find all item in association with that.
CodePudding user response:
Working TS playground.
interface GroupedItemsByCity {
cityRef: number
cityName: string,
items: Array<{
id: number,
itemName: string
}>
}
const groupedObject = returnObject.reduce<GroupedItemsByCity[]>((groupedArray, item) => {
// New slimmer item to push later
let refinedItem = {
id: item.id,
itemName: item.itemName
}
const matchedCity = groupedArray.find(city => city.cityRef === item.cityRef); // Check if the new structure already has a matching parent city for current item.
if (matchedCity) {
// If it does, push the item onto the existing city object.
matchedCity.items.push(refinedItem)
return groupedArray
}
// If it doesn't set up a new city and add the item to it
groupedArray.push({
cityRef: item.cityRef,
cityName: item.cityName,
items: [refinedItem]
})
return groupedArray
}, [])
console.log(groupedObject)