Skip to content

Instantly share code, notes, and snippets.

@jbrz0
Last active May 31, 2018 22:03
Show Gist options
  • Save jbrz0/2ba11f8808b06b949ead89dff71e39ca to your computer and use it in GitHub Desktop.
Save jbrz0/2ba11f8808b06b949ead89dff71e39ca to your computer and use it in GitHub Desktop.
Flatten Arrays in Javascript, transform multiple nested arrays into one
function flatten(ary) {
var ret = [];
for(var i = 0; i < ary.length; i++) {
if(Array.isArray(ary[i])) {
ret = ret.concat(flatten(ary[i]));
} else {
ret.push(ary[i]);
}
}
return ret;
}
var arrays = [[1,2,[3]],4];
console.log(flatten(arrays));
// [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment