Coding Challenge Practice - Question 23
dev.to·10h·
Discuss: DEV

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 ...

Similar Posts

Loading similar posts...