Flattening Arrays

suggest change

2 Dimensional arrays

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]

In ES5, we can acheive 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Arrays:
* Syntax
* Flattening Arrays

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde