简体   繁体   中英

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM