![]() |
VOOZH | about |
Flattening an array is a common JavaScript interview topic that involves converting a nested array into a single-dimensional array. While JavaScript provides the built-in flat() method, interviews often require you to write your own implementation (polyfill).
Consider the following array:
const arr = [1, 2, 3, 4, [5, 6], [[7, 8]]];Flattening this array would result in:
// Output: [1, 2, 3, 4, 5, 6, 7, 8]The goal is to transform the nested structure into a single-level array. JavaScript’s flat() method does this up to a specified depth.
The flat() method is simple to use:
const result = arr.flat();
console.log(result); // Output: [1, 2, 3, 4, 5, 6, [7, 8]]
By default, flat() only flattens the array one level deep. To flatten deeper levels, you can specify the depth as an argument:
const result = arr.flat(2);
console.log(result); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
For arrays with unknown levels of nesting, you can use Infinity:
const result = arr.flat(Infinity);
console.log(result); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
Now, let’s create our own version of the flat() method, a polyfill. This will help you understand how flat() works under the hood and prepare you for similar interview challenges.
We start by extending the Array.prototype with a new method called myFlat:
1.0, it recursively calls itself with a decremented depth. Otherwise, it pushes the element into the tempArray.Now, let’s test our myFlat method:
const arr = [1, 2, 3, 4, [5, 6], [[7, 8]]];
const result = arr.myFlat(2);
console.log(result); // Output: [1, 2, 3, 4, 5, 6, 7, 8]
This test shows that our polyfill correctly flattens the array up to the specified depth.