Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flatten a two-dimensional and multi-dimensional array
/* 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