ARRAY FLATTENING METHODS
ECMAScript 2019 added two methods to the Array
prototype, flat
()
and flatMap()
, which make array flattening operations much easier. Without these methods, flattening arrays is a nasty business which involved either an iterative or recursive solution.
Array.prototype.flatten()
The following is an example of how a simple recursive implementation might look without using these new methods:
function flatten(sourceArray, flattenedArray = []) {
for (const element of sourceArray) {
if (Array.isArray(element)) {
flatten(element, flattenedArray);
} else {
flattenedArray.push(element);
}
}
return flattenedArray;
}
const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(flatten(arr))
// [0, 1, 2, 3, 4, 5, 6]
In many ways, this example resembles a tree data structure; each element in an...