Created
March 27, 2019 07:26
-
-
Save pke/df6b03ce57a48c14387134da36f7e7e5 to your computer and use it in GitHub Desktop.
Flatten an 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
const tap = require("tap") | |
/** | |
* This function takes an array of items and flattens them. | |
* It can also handle multiply arguments. | |
* | |
* @param {array} items that can contain nested array items | |
* @return {array} flat array of input items or an empty array | |
*/ | |
function flatten(items = []) { | |
items = Array.isArray(items) ? items : Array.prototype.slice.call(arguments) | |
return items.reduce((result, item) => { | |
if (Array.isArray(item)) { | |
result = result.concat(flatten(item)) | |
} else { | |
result.push(item) | |
} | |
return result | |
}, []) | |
} | |
tap.same(flatten([[1,2,[3]],4]), [1,2,3,4]) | |
tap.same(flatten([1,2,3,4]), [1,2,3,4]) | |
tap.same(flatten(1,2,3,4), [1,2,3,4]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment