I want to flatten string[][]
into string[]
.
The advice given in dozens of SO answers is: [].concat(...arrays)
.
But that gives me this error:
Argument of type 'string[]' is not assignable to parameter of type 'ConcatArray'.
Types of property 'slice' are incompatible.
Type '(start?: number | undefined, end?: number | undefined) => string[]' is not assignable to type '(start?: number | undefined, end?: number | undefined) => never[]'.
Type 'string[]' is not assignable to type 'never[]'.
Type 'string' is not assignable to type 'never'.
Another way I tried is this:
let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]; let bar = [].concat(...foo);
Which gives a similar error:
Argument of type 'string[]' is not assignable to parameter of type 'ConcatArray'.
Why does it work for everyone but me?
To flat a JavaScript array of objects into an object, we created a function that takes array of object as only argument. It returns a flattened object with key append by its index. The time complexity is O(mn) where n is the size of array and m is the number of properties in each object.
Use the flat() method to flatten an array in TypeScript, e.g. const flat = arr. flat() . The flat method takes a parameter, which defaults to 1 and indicates how deep the nested array should be flattened. The method returns a new array with the sub-array elements concatenated into it.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
Try this:
const a = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]] const result = a.reduce((accumulator, value) => accumulator.concat(value), []); console.log(result)
You can flatten the array with flat()
let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]; let bar = foo.flat()
log
console.log(bar) // a,b,c,a,b,c,a,b,c
UPDATE
By correcting the type to string[] you can also use concat
let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]; let bar : string[] = [] bar = bar.concat(foo[0], foo[1], foo[2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With