I am currently working on creating a custom function in typescript that can flatten nested arrays efficiently.
My current implementation is as follows:
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 use of array.reduce
in the code above accomplishes the flattening task effectively. However, I am facing challenges in incorporating generics to achieve my desired outcome. The issue arises from the fact that item[prop]
defaults to type any
, lacking the ability to infer that item[prop]
should be recognized as T[TProp]
.
My goal is to create a function capable of processing a structure similar to this:
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,
},
];
This function aims to produce an output array containing all elements from the nested arrays defined within the input structure.
const result = flattenArrayByKey(objectsWithNestedProperties, 'arrayProperty');
Upon execution, the variable result
is expected to contain the values
['hello', 'world', 'nice', 'to', 'meet', 'you']
In essence, what I am seeking is a functionality akin to C#'s linq method SelectMany
.