JS Interview Question #3 (Polyfill for array.flat())
Think1s
Posted on June 2, 2022
Read more articles in Think1s
const arr = [2, 3, 4, [5, [6, 7, [8, 9]]]];
function flatArray(arr, depth = 1) {
return depth > 1
? arr.reduce((acc, curr) => {
acc = acc.concat(
Array.isArray(curr) ? flatArray(curr, depth - 1) :curr);
return acc;
}, [])
: arr;
}
console.log(flatArray(arr, Infinity));
Click here Object flattening
Read more articles in Think1s
๐ ๐ช ๐
๐ฉ
Think1s
Posted on June 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev A Tale of WeakMap and WeakSet in JavaScript: The Guardians of Forgotten Secrets
November 29, 2024