
Using the reduce method let flatArray = arr. Here when we use the spread operator on the array arr we declared above, the Spread syntax (.) allows the concatenation operation to be performed on all the elements of the array and stores the result in an empty array thus giving us a flattened array. Using the spread operator let flatArray =. An empty array and the array we declared above(arr) then concatenate all the elements(sub-arrays) passed into an empty array thus obtaining a 1-dimensional array.

Simple methods to obtain a flattened array in JavaScript a. The above array, arr, when flattened would look like: ĭifferent methods to flatten an array 1. let arr = [Īn array is called a nested array when there are arrays inside this array as its elements. Let us consider a 2-dimensional nested array as shown below.

In other words, it a process of reducing the number of dimensions of an array to a lower number.īefore we dive into the process of how a JavaScript array can be flattened, let us understand what we are trying to achieve with an example. Prophetic Kabbalah 1, 2 Rationalism 1, 2, 3, 4.
