How to write custom array flatten method in JavaScript
constnestedArray=[1,2,[4,[5,6,[[9]]]]]// Method to flat an arrayfunctionflatten(input,list=[]){input.forEach((item)=>{if(Array.isArray(item)){flatten(item,list)}else{list.push(item)}})returnlist}
// Prototype to flat an arrayArray.prototype.customFlatMap=function(){functionflatten(input,list=[]){input.forEach((item)=>{if(Array.isArray(item)){flatten(item,list)}else{list.push(item)}})returnlist}returnflatten(this)}constflatArray=nestedArray.customFlatMap()console.log({flatArray})// [ 1, 2, 4, 5, 6, 9 ]
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)