Skip to content

Instantly share code, notes, and snippets.

@rg1220
Created April 3, 2018 18:35
Show Gist options
  • Save rg1220/181af2f67f50e37998ff38ea29794b63 to your computer and use it in GitHub Desktop.
Save rg1220/181af2f67f50e37998ff38ea29794b63 to your computer and use it in GitHub Desktop.
Flatten Array
/**
* 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
};
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