Flatten Array using array.flat () in JavaScript

This post is written by Samantha Ming, a Canadian programming socialite who writes a blog called “Code Tidbits.” This blog posts some tips on JS, HTML, and CSS on a weekly basis. It is short and easy to understand, and each article is accompanied by a nice picture that summarizes the summary. We can look for, as the saying goes well ah, “teach people to fish than teach people to fish”, “their own hands, ample food and clothing” 😀.

ES2019 introduces a new flat array method, flat(). The full syntax is:

array.flat([depth]);
Copy the code

This method accepts the optional depth argument, which represents the depth of the flattening. Backpacks 🤩

const nested = [ ['📦'.'📦'], ['📦']].const flattened = nested.flat();

console.log(flattened);
/ / [' 📦 ', '📦', '📦]
Copy the code

Set the depth value to depth

The full syntax for this method has been mentioned above:

array.flat([depth]);
Copy the code

The optional depth of the flat() method, which defaults to 1, represents the depth that is flattened to one layer.

array.flat()
/ / is equivalent to
array.flat(1)
Copy the code

Deeper array flattening

The best thing about this method is that you can flatten a nested array to a depth of more than 1 layer by simply setting the depth parameter.

const twoLevelsDeep = [[1[2.2].1]].// depth = 1
twoLevelsDeep.flat()
// [1, [2, 2], 1]

// depth = 2
twoLevelsDeep.flat(2)
// [1, 2, 2, 1]
Copy the code

Flat nested arrays with many layers

If you don’t know the exact depth of the array you want to flatten and want to flatten the members of the nested array completely, use Infinity.

const veryDeep = [[1[2.2[3[4[5[6]]]]], 1]];

veryDeep.flat(Infinity);
// [1, 2, 2, 3, 4, 5, 6, 1]
Copy the code

Ignore array space

The cool thing about the flat() method is that while flattening the array, it also removes Empty Slots from the array.

const missingNumbers = [1.3.5];

missingNumbers.flat();
/ / [1, 3, 5];
Copy the code

Browser support

Because Flat () is a new feature defined in ES2019, forget Internet Explorer and Edge, 😅

Browser Support: flat

alternative

Since this approach is not well supported, there are some alternatives.

The ES6 type

The following scheme is based on the ES56 deconstruction syntax. But you can only nest arrays flat on one layer.

const oneLevelDeep = [ [1.2], [3]].constflattened = [].concat(... oneLevelDeep);/ / [1, 2, 3,]
Copy the code

Before the ES6

Similarly, the following method can only flat the array.

const oneLevelDeep = [ [1.2], [3]].const flattened = [].concat.apply([], oneLevelDeep);
/ / [1, 2, 3,]
Copy the code

Recursive flat

For flattening deeply nested arrays, you can use recursive calls. The following code is taken from the MDN documentation.

var arr1 = [1.2.3[1.2.3.4[2.3.4]]];

function flattenDeep(arr1) {
   return arr1.reduce((acc, val) = > Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
Copy the code

Note: There is a “30 second series” repository of JS code snippets that implement the same function as above:

const deepFlatten = arr => [].concat(... arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));Copy the code

There are many other code snippets in the repository that you can occasionally look at and learn from.

The resource list

  • MDN Web Docs: flat()
  • Alligator: Flatten Arrays in Vanilla JavaScript with flat and flatMap
  • Flatten array of arrays with JavaScript
  • Stack Overflow: Merge/flatten an array of arrays
  • Flattening multidimensional Arrays in JavaScript
  • Flattening Arrays in JavaScript with flat and flatMap

(after)