How to Merge/Flatten an Array of Arrays in JavaScript

Introduction

Arrays are a fundamental part of JavaScript programming. In some cases, you may encounter an array that contains nested arrays, and you may need to flatten or merge these nested arrays into a single array. In this article, we will explore different approaches to solve this problem in JavaScript, along with code examples.

Problem Description

Let's consider the following JavaScript array:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

The goal is to merge the separate inner arrays into one, resulting in the following array:

["$6", "$12", "$25", "$25", "$18", "$22", "$10"]

Solution 1: Using the concat Method

The concat method in JavaScript allows us to concatenate multiple arrays or values into a new array. We can utilize this method to merge the nested arrays into one. Here's an example:

const nestedArray = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
const mergedArray = [].concat(...nestedArray);
console.log(mergedArray);

The resulting output will be:

["$6", "$12", "$25", "$25", "$18", "$22", "$10"]

Solution 2: Using the flat Method

Starting from ECMAScript 2019, JavaScript introduced the flat() method, which allows us to flatten nested arrays. With this method, we can easily achieve the desired result. Here's an example:

const nestedArray = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
const mergedArray = nestedArray.flat();
console.log(mergedArray);

The resulting output will be the same as before:

["$6", "$12", "$25", "$25", "$18", "$22", "$10"]

Solution 3: Using the reduce Method

The reduce method in JavaScript allows us to apply a function to each element of an array and reduce it to a single value. We can leverage this method to flatten the nested arrays into one. Here's an example:

const nestedArray = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
const mergedArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
console.log(mergedArray);

The resulting output will be the same as before:

["$6", "$12", "$25", "$25", "$18", "$22", "$10"]

Solution 4: Using the flatMap Method

The flatMap method in JavaScript, introduced in ECMAScript 2019, combines the functionalities of both map and flat methods. We can utilize this method to flatten and merge the nested arrays. Here's an example:

const nestedArray = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
const mergedArray = nestedArray.flatMap(arr => arr);
console.log(mergedArray);

The resulting output will be the same as before:

["$6", "$12", "$25", "$25", "$18", "$22", "$10"]

Conclusion

Handling nested arrays and merging them into a single array is a common task in JavaScript. In this article, we explored different solutions to this problem using methods like concat, flat, reduce, and flatMap. These methods provide concise and efficient ways to flatten and merge arrays.