Array Flatten in JavaScript

What nested arrays are
Array inside array is called nested array.
Why flattening arrays is useful
One of the usecase is that we want all users post in single array to display it.
const users = [
{ name: "A", posts: ["p1", "p2"] },
{ name: "B", posts: ["p3"] }
];
const allPosts = users.map(u => u.posts).flat();
Concept of flattening arrays
One of the way to flatten the arrays is to use flat function.
flat - It takes optional depth parameter. Depth denotes how much level of depth we want array to flat. Passing Infinity will flat the whole nested array.
const arr = [1,[2,[3,[4,[5]]]]]
console.log(arr.flat(Infinity))
Different approaches to flatten arrays
Recursion
flat() method




