I am trying to create a function that can flatten nested arrays in typescript.
So far I have this:
function flattenArrayByKey<T, TProp extends keyof T>(array: T[], prop: TProp): T[TProp] {
return array.reduce((arr: T[TProp], item: T) => [...arr, ...(item[prop] || [])], []);
}
The array.reduce
in there does exactly what I want as is, but I can't get the generics to play along nicely with what I want. I think my problem is that item[prop]
returns any
since it has no way of inferring that item[prop]
returns T[TProp]
.
What I'm aiming for is a function that can take this structure:
interface MyInterface {
arrayProperty: string[];
anotherArray: number[]
someNumber: number;
}
const objectsWithNestedProperties: MyInterface[] = [
{
arrayProperty: ['hello', 'world'],
anotherArray: [1, 2],
someNumber: 1,
},
{
arrayProperty: ['nice', 'to'],
anotherArray: [3, 4],
someNumber: 2,
},
{
arrayProperty: ['meet', 'you'],
anotherArray: [5, 6],
someNumber: 3,
},
];
and return an array that contains the contents of all the nested array.
const result = flattenArrayByKey(objectsWithNestedProperties, 'arrayProperty');
result
should look like ['hello', 'world', 'nice', 'to', 'meet', 'you']
Basically I am looking for SelectMany
from C#'s linq.
Array.flat()
already works in some modern browsers