Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created June 22, 2021 23:27
Show Gist options
  • Save CarlaTeo/da9f58069d79850de5de6da91ef10df7 to your computer and use it in GitHub Desktop.
Save CarlaTeo/da9f58069d79850de5de6da91ef10df7 to your computer and use it in GitHub Desktop.
[JS] Recreate arrayFlat
function arrayFlat(array) {
return array.reduce((result, elem) => {
if(Array.isArray(elem)) {
result.push(...arrayFlat(elem));
}
else {
result.push(elem);
}
return result;
}, []);
}
// ---------------------------------------------- Test ------------------------------------------//
console.log(arrayFlat([]));
console.log(arrayFlat([1]));
console.log(arrayFlat([1,2,3]));
console.log(arrayFlat([[]]));
console.log(arrayFlat([[1,2], []]));
console.log(arrayFlat([[1], [2], [3]]));
console.log(arrayFlat([[1, [2, [3]]], [4, 5]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment