Skip to content

Instantly share code, notes, and snippets.

@BalasubramaniM
Last active August 17, 2021 15:56
Show Gist options
  • Save BalasubramaniM/24e676fdd3f858fb27be7d43253be07b to your computer and use it in GitHub Desktop.
Save BalasubramaniM/24e676fdd3f858fb27be7d43253be07b to your computer and use it in GitHub Desktop.
Array Flat Polyfill with Depth Implementation
Array.prototype.myFlat = function (depth) {
function getFlattenedArr(arr) {
let res = [];
let isSpreaded = false;
for (let value of arr) {
if (Array.isArray(value)) {
isSpreaded = true;
res.push(...value);
} else {
res.push(value);
}
}
return {
res,
isSpreaded,
};
}
let result = [...this];
let counter = 0;
while (counter < depth) {
const { res, isSpreaded } = getFlattenedArr(result);
result = res;
counter++;
if (!isSpreaded) break;
}
return result;
};
const arr = [[1, 2, 3], 4, [5, [6]], 7];
console.log(arr.myFlat(Infinity)); // [1,2,3,4,5,6,7];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment