Skip to content

Instantly share code, notes, and snippets.

@pke
Created March 27, 2019 07:26
Show Gist options
  • Save pke/df6b03ce57a48c14387134da36f7e7e5 to your computer and use it in GitHub Desktop.
Save pke/df6b03ce57a48c14387134da36f7e7e5 to your computer and use it in GitHub Desktop.
Flatten an array
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