Created
November 17, 2016 06:34
-
-
Save Nishchit14/4c6a7349b3c778f7f97b912629a9f228 to your computer and use it in GitHub Desktop.
Native flatten in ES5 and ES6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 interesting approach
@rsantoshreddy, yeah nice. But might need to escape those brackets ala (/\[|\]/g,'')
.
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
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)