Created
July 23, 2023 17:23
-
-
Save ZakriaJanjua/6b8703295d861d4b9de5e0a6f633c0b2 to your computer and use it in GitHub Desktop.
Custom flat function for arrays in javascript/node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.customFlat = function(depth = 1) { | |
let result = [] | |
for (let arr of this) { | |
if (Array.isArray(arr) && depth > 0) { | |
result.push(...arr.customFlat(depth-1)) | |
} else { | |
result.push(arr) | |
} | |
} | |
return result | |
} | |
let a = [ | |
[1,2], | |
[3,4], | |
[[5,6]], | |
[[[7,8]]], | |
[9,10] | |
] | |
console.log(a.customFlat(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment