Skip to content

Instantly share code, notes, and snippets.

@ZakriaJanjua
Created July 23, 2023 17:23
Show Gist options
  • Save ZakriaJanjua/6b8703295d861d4b9de5e0a6f633c0b2 to your computer and use it in GitHub Desktop.
Save ZakriaJanjua/6b8703295d861d4b9de5e0a6f633c0b2 to your computer and use it in GitHub Desktop.
Custom flat function for arrays in javascript/node.js
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