Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Last active February 26, 2021 23:46
Show Gist options
  • Select an option

  • Save dgowrie/ed1b416d4927388915e5 to your computer and use it in GitHub Desktop.

Select an option

Save dgowrie/ed1b416d4927388915e5 to your computer and use it in GitHub Desktop.
How to recursively flatten a nested array.
// alternative using 'instanceof' check
(function() {
'use strict';
var array = [
'l1a',
'l1b',
[
'l2a',
[
'l3a'
],
'l2c'
],
'l1d'
];
var flat = [];
function flatten(nested) {
for (var i = 0; i < nested.length; i++) {
if ( isArray(nested[i]) ) {
console.log('nested ', nested[i]);
flatten(nested[i]);
} else {
flat.push(nested[i]);
}
}
return flat;
}
function isArray(arr) {
return arr instanceof Array;
}
console.log(flatten(array));
}());
// using native Array.prototype.concat method
(function() {
'use strict';
var myArray = [
'first!',
[1,2,3],
['a','b',['nested', 'x1'],'c'],
4,
5,
[6,7,'d','e'],
['deep', ['deeper', 'deeperstill', ['deepest', 'deepest', 'yet']]],
'last!'
],
weirdArray = [[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]];
function doConcat(array) {
var flat = [];
//console.log('array being worked on: ', array);
for (var i = 0; i < array.length; i++) {
if (array[i].constructor === Array) {
//console.log('nested array found: ');
flat = flat.concat(doConcat(array[i]));
} else {
flat.push(array[i]);
//console.log('flat is now: ', flat);
}
}
return flat;
}
var flattened = doConcat(myArray);
console.log('totally flat: ', flattened);
}());
// avoiding native Array.prototype.concat method... IMHO, this is cleaner, easier to read/understand
(function() {
'use strict';
var myArray = [
'first!',
[1,2,3],
['a','b',['nested', 'x1'],'c'],
4,
5,
[6,7,'d','e'],
['deep', ['deeper', 'deeperstill', ['deepest', 'deepest', 'yet']]],
'last!'
],
weirdArray = [[[[[0]], [1]], [[[2], [3]]], [[4], [5]]]],
flat = [];
function doConcat(array) {
//console.log('array being worked on: ', array);
for (var i = 0; i < array.length; i++) {
if (array[i].constructor === Array) {
//console.log('nested array found: ');
doConcat(array[i]);
} else {
flat.push(array[i]);
//console.log('flat is now: ', flat);
}
}
}
doConcat(myArray);
console.log('totally flat: ', flat);
}());
@dgowrie

dgowrie commented Feb 5, 2015

Copy link
Copy Markdown
Author

Goal was to do this avoiding native Array.prototype.concat method... just 'cause.

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