The task is to implement the Array.prototype.flat(), which reduces nesting of an array.
The boilerplate code:
function flat(arr, depth = 1) {
// your implementation here
}
The flat method receives an array and a number to determine how many levels deep to flatten the array. If no number is provided, depth defaults to 1, because the flat method flattens by 1 by default.
An array called result, where flattened elements will be collected, is created
const result = [];
A helper function that takes 2 arguments is created to flatten the array recursively. The function loops through every index of the array. If there are indexes that don’t exist, it skips them.
const flatten = (array, currentDepth) => {
for (let i = 0; i < array.length; i++) {
if (!(i in ...
The task is to implement the Array.prototype.flat(), which reduces nesting of an array.
The boilerplate code:
function flat(arr, depth = 1) {
// your implementation here
}
The flat method receives an array and a number to determine how many levels deep to flatten the array. If no number is provided, depth defaults to 1, because the flat method flattens by 1 by default.
An array called result, where flattened elements will be collected, is created
const result = [];
A helper function that takes 2 arguments is created to flatten the array recursively. The function loops through every index of the array. If there are indexes that don’t exist, it skips them.
const flatten = (array, currentDepth) => {
for (let i = 0; i < array.length; i++) {
if (!(i in array)) {
result.push();
continue;
}
}
The function runs recursively, checking each element of the array. If the element is another array, and the specified depth isn’t reached, the function flattens it. If it’s not an array or the depth is reached, it pushes the element into the results array.
const element = array[i];
if (Array.isArray(element) && currentDepth < depth) {
flatten(element, currentDepth + 1);
} else {
result.push(element);
}
The results array is then returned. The final code looks like this:
function flat(arr, depth = 1) {
// your implementation here
const result = [];
const flatten = (array, currentDepth) => {
for (let i = 0; i < array.length; i++) {
if (!(i in array)) {
result.push();
continue;
}
const element = array[i];
if (Array.isArray(element) && currentDepth < depth) {
flatten(element, currentDepth + 1);
} else {
result.push(element);
}
}
};
flatten(arr, 0);
return result;
}
That’s all folks!