Member-only story

Javascript Interview Prep: implement Array.prototype.flat()

Marika Lam
1 min readJun 20, 2024

--

Prompt

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]

Answer

Here is an example I wrote of how to implement the flat() method. I used a recursive method to flatten the array.

Solution 1:


// This is a JavaScript coding problem from BFE.dev
/**
* @param { Array } arr
* @param { number } depth
* @returns { Array }
*/
function flat(arr, depth = 1) {
const res = [];
arr.filter((each, eachIndex) =>{
// console.log(typeof each);
if (Array.isArray(each) && depth > 0){
const flattened = flat(each, depth-1);
flattened.filter((each1, each1Index) => {
res.push(each1);
})

} else {
res.push(each)
}
});
console.log(res.toString());
return res;
}


const arr = [1, [2], [3, [4]]];

flat(arr, 1);

Solution 2:

function flat(arr, depth = 1) {
if (depth === 0) return arr;
const output = []
for (const item of arr) {
if (Array.isArray(item)) {
output.push(...flat(item, depth - 1))
} else {
output.push(item);
}
}
return output;
}


const arr = [1, [2], [3, [4]]];

console.log(flat(arr, 1));

--

--

No responses yet