Search code examples
arraystypescriptfinduniquedistinct

get distinct base on 2 or more Values from array in typescript


I have an array as shown below.

enter image description here

I want this pattern:

enter image description here

I want to Get distinct "CityRef" and "City". then find all item in association with that.


Solution

  • 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)