Skip to content

Instantly share code, notes, and snippets.

@prashantsani
Created March 5, 2020 15:03
Show Gist options
  • Select an option

  • Save prashantsani/21b6a16b58ce7ae3e361b35a0eec375f to your computer and use it in GitHub Desktop.

Select an option

Save prashantsani/21b6a16b58ce7ae3e361b35a0eec375f to your computer and use it in GitHub Desktop.
Flatten An array of Integers not using Array.flat()
// Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
// e.g. [[1,2,[3]],4] -> [1,2,3,4].
function flatten(arr){
let newArray = [];
for(let i=0; i< arr.length; i++){
if(Array.isArray(arr[i])){
newArray = newArray.concat(flatten(arr[i]))
}else{
newArray.push(arr[i])
}
}
return newArray;
}
console.log(flatten([[1,2,[3]],4]));
console.log(flatten([[1,33,22,[[[12]]],[3]],4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment