Skip to content

Instantly share code, notes, and snippets.

@kidsil
Created December 3, 2018 10:52
Show Gist options
  • Save kidsil/2888cfb37a5aff7b7e65667eba58fe4f to your computer and use it in GitHub Desktop.
Save kidsil/2888cfb37a5aff7b7e65667eba58fe4f to your computer and use it in GitHub Desktop.
Flatten Multidimensional Arrays
'use strict';
const arr = [1,[2],[[3]],[[[4]]]]; //example Array
//Solution one - classic
let flatArr = [];
const flatten = (elem) => {
if (Array.isArray(elem)) return elem.forEach(flatten);
return flatArr.push(elem);
};
arr.forEach(flatten);
console.log('Solution one: ');
console.log(flatArr);
//Solution two - clever clogs
flatArr = arr.toString().split(',').map(el => parseInt(el));
console.log('Solution two: ');
console.log(flatArr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment