Flattening means converting a nested array (an array inside arrays) into a
single level array. If I have multiple levels like [1, 2, [3, 4], [[5, 6]]], dealing with it is difficult. I don’t want arrays inside arrays at different levels. I want everything at one single level like [1, 2, 3, 4, 5, 6].
If you want to do more with array transformations after flattening, see
map-filter-reduce.
What is JavaScript Array Flattening

JavaScript Array Flattening is taking a nested array and reducing it to a single level. A multi-level array has arrays inside arrays, and the goal is to resolve those inner arrays into a flat sequence of values.
Here is the kind of nested data I am talking about:
const nested = [1, 2, [3, 4], [[5, 6]]];
I want the result as a single array.
Flat method
The first method is the built-in
Array.prototype.flat.
Step 1: Keep your original nested array.
const nested = [1, 2, [3, 4], [[5, 6]]];

Step 2: Create a new variable and call
flat on the original array.
const flattenedOnce = nested.flat();
console.log(flattenedOnce);
// [1, 2, 3, 4, [5, 6]]

By default,
flat resolves only one level. You can see [5, 6] is still inside an inner array after a single flatten. If you only need to remove one nesting level, this is enough.
If you plan to analyze values after flattening, you might want to
count frequencies.
Unknown depth
If you do not know how deep the nested arrays go, pass
Infinity to
flat. This resolves every level until you get a single level array.
Step 1: Call
flat with
Infinity.
const flattenedAll = nested.flat(Infinity);
console.log(flattenedAll);
// [1, 2, 3, 4, 5, 6]

Step 2: Work with the fully flattened result.
// example: sum the values
const sum = flattenedAll.reduce((a, b) => a + b, 0);
console.log(sum); // 21

If you are moving from data work to UI, take a look at a simple
dropdown menu pattern.
Final thoughts
Flattening arrays in JavaScript is straightforward with
flat. By default,
flat reduces one level. If you are unsure about the depth, use
flat(Infinity) to resolve all levels and get everything at the same level.