5 ways to flatten nested array in JavaScript


5 ways to flatten nested array in JavaScript

In this post, we will learn how to flatten nested arrays in JavaScript.

Flattening an array means reducing the multidimensionality of an array into a specific dimension.

Suppose we have an array of array i.e a nested array. We call it a two-dimensional array in JavaScript.

Example:

const arr = [['one','two'],['three','four'],'five']

This is called a nested array and when we flatten the array, it returns us a single one-dimensional array like this.

[ 'one', 'two', 'three', 'four', 'five' ]

How to flatten a nested array in JavaScript?

There are four different ways to flatten an array in JavaScript:

  1. Using spread operator

  2. Using concat() and apply() method

  3. Using reduce() method

  4. Using Array.flat() method.

let's see each method with an example.

Flatten nested array using spread operator and concat

The spread operator (...) takes the elements of the nested array and expands it into an individual array.

The concat() method joins two or more arrays together and returns a new array.

Example:

const nestedArr = [['one','two'],['three','four'],'five']

const oneArr = [].concat(...nestedArr)
console.log(oneArr)

Output:

[ 'one', 'two', 'three', 'four', 'five' ]

The spread syntax (...) expands the elements of the sub-arrays in the nestedArr and the return value is then stored in the empty array using the concat() method.

Using concat() and apply() method to flatten an array

The apply() method is used to call a function with a given this value, and we have to pass the second argument as an array.

const nestedArr = [['one','two'],['three','four'],'five']

const oneArr = [].concat.apply([], nestedArr);
console.log(oneArr)

Output:

[ 'one', 'two', 'three', 'four', 'five' ]

Here, in the above example, this (first argument) is an empty array, and the second argument is the nestedArr.

First, we merged the NestedArr with this argument and then passed and joined the result to a new empty array using concat() method.

Read more about [apply()](JavaScript Function apply() Method) here.

Using reduce() method to flatten array

The reduce() method executes a reducer callback function upon each element in an array. We pass the reducer as an argument on each element in the reduce method in Javascript.

const nestedArr = [['one','two'],['three','four'],'five']

let sinlgeArr = nestedArr.reduce((acc, val) => {
    return acc.concat(val)
}, []);

console.log(sinlgeArr)

Output:

[ 'one', 'two', 'three', 'four', 'five' ]

In the above code, the reducer callback function is applied to each element in the nested array, which gives us a single value as an output. Next, we used the concat() to store the single values in an empty array.

Using flat() to flatten an array of multiple dimensions

The Array.flat() method is used to create a new array by flattening all the sub-array elements of an array up to a specific depth. The depth specifies how deep a nested array should be flattened.

arr.flat(depth)

Let's say we have a nested array like this.

const nestedArr = [['one','two'],['three','four',[1,2]],'five']

Now we will use the flat() method to get a flattened array from it.

const nestedArr = [['one','two'],['three','four',[1,2]],'five']

let arr1 = nestedArr.flat()

let arr2 = nestedArr.flat(2)

console.log(arr1) 
//[ 'one', 'two', 'three', 'four', [ 1, 2 ], 'five' ]
console.log(arr2)
//[ 'one', 'two', 'three', 'four', 1, 2, 'five' ]

In the above example, in arr1 we have flattened the nested array up to depth 1.

By default the depth is 1, so when we don't pass any value to flat(), it only flattens the array up to depth 1 only.

And in the arr2, we have flattened the array up to depth 2, so we get an array with all the elements as individual elements.

Using flatMap() method to flatten multi-dimensional array.

The flatMap() method creates a new array by applying a callback function on each sub-array in it up to level one depth.

Example:

let nestedArr = [['one','two'],['three','four'],'five']

let flatten = nestedArr.flatMap(el=>el)

console.log(flatten)

Output:

[ 'one', 'two', 'three', 'four', 'five' ]

Related Topics:

Convert array to string with brackets and quotes in JavaScript

How to convert an array to string in Javascript

5 Ways to Empty an Array

Compare Elements of Two Arrays in JavaScript

How to copy or clone an array in JavaScript