Skip to content

Instantly share code, notes, and snippets.

@JDMcKinstry
Last active March 29, 2017 20:52
Show Gist options
  • Save JDMcKinstry/43bf3ae8f171413abba5f89276d06529 to your computer and use it in GitHub Desktop.
Save JDMcKinstry/43bf3ae8f171413abba5f89276d06529 to your computer and use it in GitHub Desktop.
/** make_flat(Array)
* Simple method for flattening a multidimensional array
* @example make_flat([[1,2,[3]],4]) == [1, 2, 3, 4]
**/
function make_flat(arr) {
// simply make use of `reduce` method to to reduce each element to a single val
return arr.reduce(function(a, b) {
// if val is array, rerun thru, else, move on
return a.concat( Array.isArray(b) ? make_flat(b) : b );
},
[]
);
}
/* arbitrarily, for simplicity, could be written using a simple arrow function as:
function make_flat(arr) {
return arr.reduce( (acc, val) => acc.concat( Array.isArray(val) ? make_flat(val) : val ), [] );
}
*/
/** See Simple Test @
* https://jsperf.com/flatten-js-array/1
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment