JavaScript Array flat() method flattens an array of Objects and returns a flattened array of Objects.
Syntax
Array.flat(argument)
Parameters
It is several levels at which level you want to flatten an object.
Example
Let’s say we have an array of nested objects and need to flatten that Array.
const users = [
[{ id: 1, name: 'Alice' }, { id: 3, name: 'Bob' }],
[
[
{ id: 7, name: 'Calvin' },
{ id: 2, name: 'Doe' }
],
],
];
To flatten this Array of objects, use Infinity as an argument to the flat() function.
const flattenedArray = users.flat(Infinity);
console.log(flattenedArray);
Output
[
{ id: 1, name: 'Alice' },
{ id: 3, name: 'Bob' },
{ id: 7, name: 'Calvin' },
{ id: 2, name: 'Doe' }
]
Here, we took Infinity as an argument; it will flatten all the objects at a base level, No matter how deeply Nested.
So, if you want to flatten the Array on some predefined level, you can declare that as an argument.
Let’s take an example of a custom-defined argument.
const flattenedArray = users.flat(3);
console.log(flattenedArray);
Output
[
{ id: 1, name: 'Alice' },
{ id: 3, name: 'Bob' },
{ id: 7, name: 'Calvin' },
{ id: 2, name: 'Doe' }
]
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.