I was looking for a way to separate an array into 2 arrays given a validation function & found this question that helped a lot. The answer is the following:
function partition(array, isValid) {
return array.reduce(([pass, fail], elem) => {
return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
}, [[], []]);
}
const [pass, fail] = partition(myArray, (e) => e > 5);
Now I want to write the same question but now using typescript:
const separateArray = <T>(array: T[], condition: (e: T) => boolean): [T[], T[]] => {
return array.reduce(([passed, failed], elem: T) => condition(elem) ? [
[...passed, elem], failed
] : [passed, [...failed, elem]],[[],[]])
}
The above works just fine, the thing is that when I try to set the type for the first param of the reduce
function TO [T[], T[]]
I get an error:
Code:
return array.reduce(([passed, failed]: [T[], T[]] ......
Error:
Type 'T[][]' is not assignable to type '[T[], T[]]'.
Target requires 2 element(s) but source may have fewer.
I tried setting the type to [any[],any[]]
and [any, any]
but I still get the same error.
Does anyone know how can I solve this?