Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten array of arrays in TypeScript

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?

like image 703
lonix Avatar asked Jun 11 '19 13:06

lonix


People also ask

How do you flatten an array of objects in TypeScript?

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.

How do I flatten a list in TypeScript?

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.

How do I merge an array of arrays into a single array?

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.


2 Answers

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)
like image 169
Ghoul Ahmed Avatar answered Sep 25 '22 14:09

Ghoul Ahmed


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]) 
like image 24
Kokodoko Avatar answered Sep 22 '22 14:09

Kokodoko