Shipwell JS Interview
by Thomas Upton
HTML
<script src="https://cdn.jsdelivr.net/gh/eu81273/jsfiddle-console/console.js"></script>
JavaScript
const flatten = (arr) => {
// Convert a multi-dimensional array
// into a single-dimentional array
return arr.reduce((flattened, list) => [ ...flattened, ...(Array.isArray(list) ? flatten(list) : [list]) ], []);
}
const arrayOne = [1, 2, [3, 4]];
console.log(flatten(arrayOne));
// should log: [1, 2, 3, 4]
const arrayTwo = [[1, 2], [3, 4, 5], [6, 7, 8, 9]];
console.log(flatten(arrayTwo));
// should log: [1, 2, 3, 4, 5, 6, 7, 8, 9]
const arrayThree = [[1, 2], 3, [4, [5]]];
console.log(flatten(arrayThree));
// should log: [1, 2, 3, 4, 5]