Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented May 4, 2017

@rsantoshreddy interesting approach

@rosschapman

This comment has been minimized.

Copy link

commented Nov 7, 2017

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

@scagood

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.