Created
January 25, 2019 10:20
-
-
Save pke/baea4c6ed1d644c55d67e676921f4616 to your computer and use it in GitHub Desktop.
Flatten array items
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