Typescript flatMap, flat, flatten doesn't exist on type any[]
You should add es2019
or es2019.array
to your --lib
setting for TypeScript to recognize array.flat()
and flatMap()
.
Example:
{
"compilerOptions": {
"target": "es5",
"lib": [
"es2019"
]
}
}
Previously this was available as part of esnext
or esnext.array
, but it's now officially part of ES2019.
Aaron Beall's answer is excellent. It may be worth knowing that if "lib" is not specified in the tsConfig.JSON file a default list of libraries are injected. The default libraries injected are: ► For --target ES5: DOM,ES5,ScriptHost ► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost
In other words: We must specify those libs that were previously added automatically. (see: https://www.typescriptlang.org/docs/handbook/compiler-options.html for further info)
"compilerOptions": {
"target": "es6",
"lib": [ "es2019", "DOM", "ES6" ,"DOM.Iterable", "ScriptHost"],}
To flat single level array
arr.reduce((acc, val) => acc.concat(val), []);
To flat multi level array
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), []) : arr.slice();
};
to know deeply you can also check below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat