Skip to content

Instantly share code, notes, and snippets.

@Nishchit14
Created November 17, 2016 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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]
@rsantoshreddy
Copy link

rsantoshreddy commented Apr 21, 2017

var x=[1, 2, [3, 4, [5, 6,[7], 9],12, [12, 14]]];
var y=JSON.parse(`[${JSON.stringify(x).replace(/[|]/g,'')}]`);
console.log(y)

@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