Created
April 3, 2018 18:35
-
-
Save rg1220/181af2f67f50e37998ff38ea29794b63 to your computer and use it in GitHub Desktop.
Flatten Array
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
/** | |
* Recursive function to flatten the current array level | |
* @param {Array<any>} arr - The array to flatten | |
* @returns {Array<any>} New flattened array | |
*/ | |
const flatten = (arr) => { | |
const newArray = []; | |
arr.forEach((item) => { | |
if (Array.isArray(item)) { | |
newArray.push(...flatten(item)); | |
} else { | |
newArray.push(item); | |
} | |
}); | |
return newArray; | |
}; | |
module.exports = { | |
flatten: flatten | |
}; |
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
const { flatten } = require('./flatten'); | |
const arr = [[1,2,[3]],4]; | |
const flattedArray = flatten(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment