How to flatten an array in JavaScript

Introduction:

The process of flattening an array transforms an array from n dimensions down to a single dimension. In straightforward terms, this involves merging multiple nested arrays into one comprehensive array, resulting in a singular, one-dimensional array.

The process of reducing the dimensions of an array is referred to as flattening. This technique entails merging all the nested elements contained within an array into a singular one-dimensional array.

For example:-

Example

Original Array : [5,7,[2,1,10],[9,3,4,8],6] 

Flattened Array : [5,7,2,1,10,9,3,4,8,6]

Concat and apply in JavaScript to Flatten an Array:

This function simplifies a nested array in JavaScript by utilizing the concat method in conjunction with the apply method.

Implementation in javascript:

Example

arr = [1,2,[3,4,5],[6,7,8,9],10] 

console.log("Original Array: ",arr)

let flattened_array = [].concat.apply([], arr);

console.log("Flattened Array: ", flattened_array)

Output:

Output

Original Array:  [ 1, 2, [ 3, 4, 5 ], [ 6, 7, 8, 9 ], 10 ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial phase, we constructed an array that we aim to flatten. Subsequently, the array was flattened by utilizing the concat and apply methods. The concat function serves to merge the output, resulting in a unified array after an array of parameters is passed as an argument, effectively transforming the array into a single dimension. We have now displayed our array, which has undergone the flattening process.

Program in JavaScript to Flatten an Array Using the Spread Operator in ES6:

By utilizing this method, we will flatten an array in JavaScript by employing the Spread Operator introduced in ES6.

Implementation in javascript:

Example

arr = [1,2,[3,4,5],[6,7,8,9],10] 

console.log("Original Array: ",arr)

let flattened_array=  [].concat(...arr);

console.log("Flattened Array: ", flattened_array)

Output:

Output

Original Array:  [ 1, 2, [ 3, 4, 5 ], [ 6, 7, 8, 9 ], 10 ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial phase, we constructed an array that we intend to flatten. To achieve this, we utilized the Spread Operator introduced in ES6 ('...'). By employing the concat function, we can join the outcome, resulting in a unified array when the Spread Operator "..." is applied prior to the array for flattening purposes. We have now displayed our array after it has been flattened.

Program in JavaScript to Flatten an Array Using the reduce approach:

In this approach, we will simplify a nested array in JavaScript through the utilization of the reduce method.

Implementation in javascript:

Example

arr = [1,2,[3,4,5],[6,7,8,9],10] 

console.log("Original Array: ",arr)

let flattened_array = arr.reduce((acc, val) => {

    return acc.concat(val)

}, []);

console.log("Flattened Array: ", flattened_array)

Output:

Output

Original Array:  [ 1, 2, [ 3, 4, 5 ], [ 6, 7, 8, 9 ], 10 ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial step, we constructed an array that we aim to simplify. Subsequently, we utilized the reduce method to flatten this array. At this point, we have displayed our newly flattened array.

Program in JavaScript to Flatten an Array Using forEach :

In this tutorial, we will utilize the forEach loop to flatten an array in JavaScript.

Implementation in javascript:

Example

const arr = [[1,2],[3,4,5],[6,7,8,9],[10]];

console.log("Original Array: ",arr)

const flattened_array = []

arr.forEach(array => {

flattened_array.push(...array);

});

console.log("Flattened Array: ", flattened_array)

Output:

Output

Original Array:  [ [ 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8, 9 ], [ 10 ] ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial phase, we created an array that we intend to simplify. Subsequently, we utilized the forEach loop to achieve the flattening of this array. Inside the forEach loop, we employed the Spread operator '...' to flatten the array. We have now displayed the array after it has been flattened.

Program in JavaScript to Flatten an Array Using Reduce, Concat, and IsArray:

This approach simplifies an array in JavaScript by consistently employing the reduce, concat, and isArray functions.

Implementation in javascript:

Example

const arr = [1,2,[3,4,5],[6,7,8,9],10] 

console.log("Original Array: ",arr)

function flatten (arr) {

      var flattened_arr = [];

      for (var i = 0; i<arr.length; i++) {

        if (Array.isArray(arr[i])) {

flattened_arr = flattened_arr.concat(flatten(arr[i]));

        } else {

flattened_arr.push(arr[i]);

        }

      }

      return flattened_arr;

    }

console.log("Flattened Array: ", flatten(arr))

Output:

Output

Original Array:  [ 1, 2, [ 3, 4, 5 ], [ 6, 7, 8, 9 ], 10 ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial phase, we created an array that we aim to flatten. Subsequently, we utilized the concat and isArray functions to achieve this flattening process. The isArray method processes each item of the array individually and passes them as arguments, allowing the concat function to combine these results into a single array. Finally, we have displayed the array that has undergone flattening.

Program in JavaScript to Flatten an Array Using a while loop and a recursive helper function:

This method simplifies a JavaScript array by employing a while loop in conjunction with a recursive auxiliary function.

Implementation in javascript:

Example

const arr = [1,2,[3,4,5],[6,7,8,9],10] 

console.log("Original Array: ",arr)

const flatten = (nested) => {

const flattened_array = [];

const helper = (array) => {

    let counter = 0

    while (counter <array.length) {

const val = array[counter];

      if (Array.isArray(val)) {

        helper(val);

      } else {

flattened_array.push(val)

      }

      counter++;

    }

  }

  helper(nested);

  return flattened_array;

}

console.log("Flattened Array: ", flatten(arr))

Output:

Output

Original Array:  [ [ 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8, 9 ], [ 10 ] ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial phase, we constructed an array that we aim to flatten. Subsequently, we utilized a stack along with the isArray function to achieve the flattening process. The isArray function accepts an array as its argument, processing one element at a time. If the value of the provided parameter contains multiple elements, the array will be flattened by employing the spread operator, and the extra elements will be appended to the stack. Conversely, if the supplied parameter consists of only a single item, we will simply incorporate that item into the final collection. In the end, we return this array after reversing the resulting flattened array.

Program in JavaScript to Flatten an Array Using a Generator Function:

This approach collapses a multi-dimensional array in JavaScript through the utilization of a generator function.

Implementation in javascript:

Example

const arr = [1,2,[3,4,5],[6,7,8,9],10]; 

console.log("Original Array: ",arr)

function* flatten(array, depth) {

if(depth === undefined) {

      depth = 1;

    }

for(const val of array) {

if(Array.isArray(val) && depth > 0) {

          yield* flatten(val, depth - 1);

        } else {

          yield val;

        }

    }

}

const flattened_arr = [...flatten(arr, Infinity)];

console.log("Flattened Array: ", flattened_arr)

Output:

Output

Original Array:  [ 1, 2, [ 3, 4, 5 ], [ 6, 7, 8, 9 ], 10 ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

In the initial phase, we constructed an array that we aim to flatten. Subsequently, this array was flattened utilizing a generator function. The generator function is designed to take two parameters: array and depth. The depth specifies the maximum level of nesting within the array. Inside the generator function, the yield keyword is employed to initiate or terminate the generator's operation. This function consistently utilizes the term "yield" to output any value that it processes. At this point, we have displayed the resulting flattened array.

Program in JavaScript to Flatten an Array Using the flat Method:

This method involves flattening an array in JavaScript by utilizing the flat method. In this instance, an error is illustrated along with the variable arr. It is important to note that the flat method is exclusively supported in NodeJS and is not compatible with several web browsers, leading to the error indicating that flat is not a function.

Implementation in javascript:

Example

const arr = [1,2,[3,4,5],[6,7,8,9],10] 

console.log("Original Array: ",arr)

flattened_arr = arr.flat();

console.log("Flattened Array: ", flattened_arr)

Output:

Output

Original Array:  [ 1, 2, [ 3, 4, 5 ], [ 6, 7, 8, 9 ], 10 ]

Flattened Array:  [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

Working mechanism:

Initially, we created an array that we aim to simplify by flattening it. The flattening process was accomplished by utilizing the flat function. This function takes an array as its parameter and returns a simplified version of that array. Subsequently, we have displayed the array after it has been flattened.

Conclusion:

Following our discussion of several methods for flattening an array in JavaScript, we may draw the following conclusions.

  • The process of flattening an array reduces its dimensions from n dimensions to one
  • The entire array's nested elements are removed and combined into a single one-dimensional array.
  • When a generator function returns any value, it does so with the aid of the yield The yield keyword is used to restart or pause the generator function.
  • Although NodeJS supports the flat method, many browsers do not, which may result in an error.

Input Required

This code uses input(). Please provide values below: