An array containing primitive values, objects and other arrays can be flattened using a recursive reduce
function.
const flatten = < T = any > (arr: T[]) => {
const reducer = < T = any > (prev: T[], curr: T | T[]) => {
if (curr.constructor !== Array) {
return [...prev, curr];
}
return curr.reduce(reducer, prev);
};
return arr.reduce(reducer, []);
};
For example:
const values = [1, 2, 3, 4, [5, 6], 7, [8, [9]]];
const flatValues = flatten(values);
console.log(flatValues);
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]