Consider the array below with multiple dimensions:
type ParsedLine = [string, string];
type ParsedLines = [ParsedLine, ParsedLine]
const myArray: (ParsedLine | ParsedLines)[] = [
['something', 'somethingElse'],
[['foo', 'bar'], ['baz','qux']],
['another', 'yetAnother']
];
The expected outcome is a 2-dimensional array:
// [['something','something-else'],['foo','bar'],['baz','qux'],['another','yetAnother']]
I have explored the flatten method from Lodash, but it only produces a 1-dimensional array.
Currently, I am using the following approach:
flattenArray(multidimensionalArray: (ParsedLine | ParsedLines)[]): ParsedLine[] {
const flatArray: ParsedLine[] = [];
multidimensionalArray.forEach((item): any => {
// Why does 'item' need a typecast here?
const containsSubArray = (item as Array <ParsedLine>).filter((subItem) => Array.isArray(subItem));
if (containsSubArray.length === 0) {
flatArray.push(item as ParsedLine);
} else {
flatArray.push((item as ParsedLines)[0]);
flatArray.push((item as ParsedLines)[1]);
}
});
return flatArray;
}
console.log(flattenArray(myArray));
Although this code provides the correct output, it lacks readability and immutability due to the use of the push method.
Furthermore, the necessity to cast 'item' raises questions about whether .filter() can work effectively on the ParsedLine tuple type.