0

How can I type the reduce function parameters.

interface IGroupArrayByKey<T> {
    data: T[]
    key: string
}

export const groupArrayByKey = <T>({ data, key }: IGroupArrayByKey<T>): object => {
    return data.reduce((acc: any, item: any) => {
        return { ...acc, [item[key]]: [...(acc[item[key]] || []), item] }
    }, {})
}

groupArrayByKey function works on the principle that you provide the array as a date and key which the array should be grouped

1 Answer 1

2

Couple of notes:

  1. keyof T lists all properties of type T and doesn't allow passing arbitrary string that is not a key of the object there. Very useful imho.
  2. We cannot guarantee that item[keyProp] is a string, but indexer in an object could only be a string or a number. That's why this ugly as unknown as string. If you would have used a Map, then we wouldn't need the cast.
interface IGroupArrayByKey<T> {
    data: T[]
    keyProp: keyof T
}

export const groupArrayByKey = <T>({ data, keyProp }: IGroupArrayByKey<T>) => {
    return data.reduce<{ [key: string]: T[] }>((acc, item) => {
        const key = item[keyProp] as unknown as string;
        return { ...acc, [key]: [...(acc[key] || []), item] }
    }, {})
}
Sign up to request clarification or add additional context in comments.

1 Comment

The above answer is a great solution, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.