Skip to content

Instantly share code, notes, and snippets.

@Nishchit14
Created November 17, 2016 06:34
Show Gist options
  • Save Nishchit14/4c6a7349b3c778f7f97b912629a9f228 to your computer and use it in GitHub Desktop.
Save Nishchit14/4c6a7349b3c778f7f97b912629a9f228 to your computer and use it in GitHub Desktop.
Native flatten in ES5 and ES6
//ES5 example
var flattenES5 = function (arr) {
return [].concat.apply([], arr.map(function (element) {
return Array.isArray(element) ? flatten(element) : element;
}))
}
//ES6 example
let flattenES6 = arr => [].concat.apply([], arr.map(element => Array.isArray(element) ? flatten(element) : element))
//e.g. [[1,2,[3]],4] -> [1,2,3,4].
var arr = [[1,2,[3]],4];
flattenES5(arr);
flattenES6(arr)
//output
//[1,2,3,4]
//[1,2,3,4]
@pietrovismara
Copy link

@rsantoshreddy interesting approach

@rosschapman
Copy link

rosschapman commented Nov 7, 2017

@rsantoshreddy, yeah nice. But might need to escape those brackets ala (/\[|\]/g,'').

@scagood
Copy link

scagood commented Mar 5, 2018

Here is another take on the ES6 version:

let flatten = array => Array.isArray(array)
  ? [].concat(...array.map(flatten))
  : array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment