Hello friends, in this article I'm going to discuss and walk through my thought process of solving the implement Array.prototype.flat()
problem on BFE.dev.
Here's the question
There is already Array.prototype.flat() in JavaScript (ES2019), which reduces the nesting of Array. Could you manage to implement your own one?. Here is an example to illustrate
const arr = [1, [2], [3, [4]]];
flat(arr)
// [1, 2, 3, [4]]
flat(arr, 1)
// [1, 2, 3, [4]]
flat(arr, 2)
// [1, 2, 3, 4]
follow up: Are you able to solve it both recursively and iteratively?
Here's my recursive approach
/**
* @param { Array } arr
* @param { number } depth
* @returns { Array }
*/
function flat(arr, depth = 1) {
// let's take an array to store the final result
let flattenedArr = []
//base condition: If the depth is 0 we should return the original array
if(depth ==0 ) return arr
// traverse through the elements of the given array
arr.forEach(ele => {
// find if the element is an array and if it is an array,
// recursively call the flat function while reducing the depth by 1
if(Array.isArray(ele)){
flattenedArr = flattenedArr.concat(flat(ele, depth-1))
}
// else, we can directly add the element into the array
else {
flattenedArr = flattenedArr.concat(ele)
}
})
// finally, return the flattended array
return flattenedArr
}
Here's my iterative approach
/**
* @param { Array } arr
* @param { number } depth
* @returns { Array }
*/
function flat(arr, depth = 1) {
// let's take an array to store final result
const flattenedArr = []
// To do this problem iteratily we need either stack or queue,
// let's take stack that stores value of the element with the depth
const stack = [...arr.map(ele => [ele, depth])]
// loop though the stack until it's length is valid
while(stack.length > 0){
//let's destructure the current top along with it's depth and pop it out from stack
const [top, depth] = stack.pop()
// if the current top is an array and has a valid depth,
// push the modified array with the elements and the depth reduced to 1
if(Array.isArray(top) && depth > 0){
stack.push(...top.map(ele => [ele, depth - 1]))
}
// else, push the value of top to the flattendArr
else{
flattenedArr.push(top)
}
}
// As we started the process from the last element,
// we need to reverse the array to return the final result
return flattenedArr.reverse()
}
Conclusion
Thanks for going through the problem, I'll be adding more problems in the blog as I continue to practice, feel free to like, share & comment your feedback.