The following example flats an array with two level depth: const numbers = ]] Output: ] Code language: JavaScript ( javascript ) Note that the flat() method creates a new array and doesn’t change the original array: console.log(numbers) Code language: JavaScript ( javascript ) The flat() method concatenated all the elements of the nested array to the elements of the new array. In this example, we didn’t pass the depth argument into the flat() method therefore the depth is 1 by default. Output: Code language: JSON / JSON with Comments ( json ) The following example shows how to flat an array of numbers: const numbers = ] Ĭonsole.log(flatNumbers) Code language: JavaScript ( javascript ) The depth parameter specifies how deep the method flats the array structure.
The following shows the syntax of the flat() method: let newArray = arrayObject.flat() Code language: JavaScript ( javascript ) Introduction to the JavaScript Array flat() methodĮS2019 introduced the () method that creates a new array with all the elements of the subarrays concatenated to it recursively up to a specified depth. Summary: in this tutorial, you’ll learn how to use the JavaScript Array flat() method to flat an array.