Skip to main content

Flattening Arrays

2 Dimensional arrays

Version ≥ 6

In ES6, we can flatten the array by the spread operator ...:

function flattenES6(arr) { 
return [].concat(...arr);
}
var arrL1 = [1, 2, [3, 4]];
console.log(flattenES6(arrL1)); // [1, 2, 3, 4]

Version ≥ 5

In ES5, we can achieve that by .apply():

function flatten(arr) {
return [].concat.apply([], arr);
}

var arrL1 = [1, 2, [3, 4]];
console.log(flatten(arrL1)); // [1, 2, 3, 4]

Higher Dimension Arrays

Given a deeply nested array like so

var deeplyNested = [4,[5,6,[7,8],9]];

It can be flattened with this magic

console.log(String(deeplyNested).split(',').map(Number);
#=> [4,5,6,7,8,9]

Or

const flatten = deeplyNested.toString().split(',').map(Number) console.log(flatten);
#=> [4,5,6,7,8,9]

Both of the above methods only work when the array is made up exclusively of numbers. A multi-dimensional array of objects cannot be flattened by this method.