Created
August 6, 2020 16:10
-
-
Save martingaido/dc25b77f6575b4196bfa51caf7e12a6c to your computer and use it in GitHub Desktop.
Flatten a two-dimensional and multi-dimensional array
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
/* Flatter Arrays */ | |
'use strict'; | |
// Case 1 (two-dimensional array) | |
let array1 = [1, 2, [4, 5, 6], 8, [9, 10], 11]; | |
let newArray1 = array1.flat(); | |
console.log(newArray1); | |
// Case 2 (multi-dimensional array, wrong) | |
let array2 = [1, 2, [4, 5, 6], 8, [9, 10, [12, 13, 14]], 15]; | |
let newArray2 = array2.flat(); | |
console.log(newArray2); | |
// Case 3 (multi-dimensional array, resolved) | |
let array3 = [1, 2, [4, 5, 6], 8, [9, 10, [12, 13, 14]], 15]; | |
function flatten(input) { | |
const stack = [...input]; | |
const res = []; | |
while(stack.length) { | |
// pop value from stack | |
const next = stack.pop(); | |
if(Array.isArray(next)) { | |
// push back array items | |
stack.push(...next); | |
} else { | |
res.push(next); | |
} | |
} | |
// reverse to restore input order | |
return res.reverse(); | |
} | |
let newArray3 = flatten(array3); | |
console.log(newArray3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment