Last active
August 23, 2016 06:20
-
-
Save MurhafSousli/296859e76ffb531aa4c3318d13260b7c to your computer and use it in GitHub Desktop.
Javascript array flattening
This file contains hidden or 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
/** | |
* Flattens an array of arbitrarily nested arrays into | |
* a flat array. e.g. [[1,2,[3]],4] -> [1,2,3,4] | |
* | |
* @param items - source array | |
* @return - flat array | |
*/ | |
function flatten(items) { | |
const flat = []; | |
items.forEach(item => { | |
if (Array.isArray(item)) { | |
flat.push(...flatten(item)); | |
} else { | |
flat.push(item); | |
} | |
}); | |
return flat; | |
} | |
/** @TEST */ | |
var arr = [[1,2,[3]],4]; | |
console.log('before: ' + JSON.stringify(arr)); | |
console.log('after: ' + JSON.stringify(flatten(arr))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment