5 Easy Ways to Flatten an Array in JavaScript

Here are 5 ways to flatten an array in JavaScript.

  1. Using Array flat() method
  2. Using Array reduce() method
  3. Using Array concat() method
  4. Using a spread operator
  5. Using a recursive function

Method 1: Using the Array flat() method

The Array.prototype.flat() method creates a new array with all sub-array elements concatenated recursively up to the specified depth and returns a new array with the sub-array elements concatenated.

Syntax

let newArray = arr.flat([depth]);

Visual Representation

Visual Representation of Using the Array flat() method

Example

const arr = [['krunal', 'ankit'], [21, 74], ['appdividend', ['PHP', 'JS']]];

console.log(arr.flat(2));

Output

[ 'krunal', 'ankit', 21, 74, 'appdividend', 'PHP', 'JS' ]

Method 2: Using the Array reduce() method

The Array.reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Visual Representation

Visual Representation of Using the Array flat() method

Example

const arr = [11, [21, 30, 46], 19];

const flatten_arr = arr.reduce((acc, val) => acc.concat(val), []);

console.log(flatten_arr)

Output

[ 11, 21, 30, 46, 19 ]

Method 3: Using the Array concat() method

The  array.concat() method is to merge two or more arrays. It concatenates all the elements of an array into a new, flattened array.

Visual Representation

Visual Representation of Using the Array concat() method

Example

const arr = [11, [21, 30, 46], 19];

const flatten_arr = [].concat.apply([], arr);

console.log(flatten_arr)

Output

[ 11, 21, 30, 46, 19 ] 

Method 4: Using the spread operator

The SpreadOperator(…) allows splitting an array into single arguments passed to the function as separate arguments.

Visual Representation

Visual Representation of Using the spread operator

Example

const arr = [11, [21, 30, 46], 19];

const flatten_arr = [].concat(...arr);

console.log(flatten_arr)

Output

[ 11, 21, 30, 46, 19 ] 

Method 5: Using a recursive function

The recursive approach will comprehensively flatten an array, regardless of how many levels of nested arrays it contains.

To flatten an n-dimensional array in JavaScript, use the recursive function.

function flatten(arr) {
  return arr.reduce(
    (acc, val) =>
    Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val),
  []
 );
}

const arr = [11, [21, 30, 46], 19];
const flatten_arr = flatten(arr)
console.log(flatten_arr)

Output

[ 11, 21, 30, 46, 19 ] 

Conclusion

The best and most reliable way to flatten an array is to use the Array.flat() method.

To flatten an n-level or n-dimensional array, use the recursive function.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.