Array Flatten in JavaScript

What nested arrays are
Nested means nested. Arrays means arrays, so nested arrays means nested arrays, as simple as that.
Here is an nested array.
[1, 2, [3, 4], 5, [6, [7, 8], 9]]
This is a different view of the same array.
[
1,
2,
[
3,
4
],
5,
[
6,
[
7,
8
],
9
]
]
Why flattening arrays is useful
Let's say you want to find a reaction average of your online friend group, coz you don't have a real friend group, since your a dev so you're not social, even on the internet you only got 2 friends.
Here is the rejection array, containing three arrays with the names of the girls who rejected each of you.
const rejections = [["g1", "g2", "g3"], ["g1", "g2", "g3", "g4", "g5"], ["g1"]];
If you want to find the average, you have to find the total number of rejections, but since this is a nested array you can't just use .length or loop through it.
By flattening the array you will have one array which will have all the elements of all the nested arrays, and then you can use the .length to find the total number of rejections.
For flattening an array an array method is flat() is used, which returns a new flattened array.
const flattenedRejectionArray = rejections.flat();
console.log(flattenedRejectionArray); // ["g1", "g2", "g3", "g1", "g2", "g3", "g4", "g5", "g1"]
const averageRejection = flattenedRejectionArray.length / 3;
console.log(averageRejection); // 3
The flat() method accepts an argument, which is the depth level specifying how deep a nested array structure should be flattened, the default is 1.
If you're unsure about the depth of the nesting (just like were unaware of her manipulation skills) and want to fully flatten the array, you can use Infinity as the argument. This will return a completely flattened array.
const nested = [1, [2, [3, 4, 5, [6, 7, 8, [9]]]]];
console.log(nested.flat()); // [1, 2, [3, 4, 5, [6, 7, 8, [9]]]];
console.log(nested.flat(2)); // [1, 2, 3, 4, 5, [6, 7, 8, [9]]];
console.log(nested.flat(infinity)); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
Final thoughts
If your workings with some api which gives a nested array in response and you're not sure of the depth of it, just use flat(infinity).
For more understanding play with this method (just like she played with your feelings), use it with different arrays with different depth of nesting, also try using it on an object, you'll find something interesting.
And lastly don't forget to enjoy the coding.


