How to Merge/Flatten an array of arrays in JavaScript ?
Last Updated :
08 Nov, 2024
Merging or flattening an array of arrays in JavaScript involves combining multiple nested arrays into a single-level array. This process involves iterating through each nested array and appending its elements to a new array, resulting in a flattened structure.
To Merge or flatten array we can use array.flat() method. This method creates a new array with all sub-array elements concatenated into it.
Syntax
array.flat();
JavaScript
// Given a nested array
let array = [10, [20, 30], [40, [50, 60]], 70];
// Flatten the array to a single level
let flatArray = array.flat(Infinity);
// Display the flattened array
console.log("Updated Array:", flatArray);
OutputUpdated Array: [
10, 20, 30, 40,
50, 60, 70
]
Using Spread Operator and array.concat() Method
The spread operator is used to expand the iterables into separate value and array concat() method is used to merge the arrays into single array.
Syntax
const arr = [ 10, 20, 30 ];
// Separates the array values to individual elements
let [first, second, third] = [...arr];
JavaScript
// Given nested array
let array = [10, [20, 30], [40, 50, 60], 70];
// Flatten the array to a single level
let flatArray = [].concat(...array);
// Display the flattened array
console.log("Updated Array:", flatArray);
OutputUpdated Array: [
10, 20, 30, 40,
50, 60, 70
]
Note: It only works to flaten single level of nested array.
Using Underscore.js _.flatten() Function
Underscore.js _.flatten() Function is an inbuilt function in the Underscore.js library of JavaScript which is used to flatten an array that is nested to some level.
For installing Underscore.js, use the below command:
npm install underscore
Or use this cdn in the script tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.1/underscore-min.js"></script>
JavaScript
// Given nested array
let array = [10, [20, 30], [40, [50, 60]], 70];
// Use _.flatten() to fully flatten the array
let flatArray = _.flatten(array, true); // Pass true to flatten deeply
// Display the flattened array
console.log("Updated Array:", flatArray);
Output
Updated Array: [ 10, 20, 30, 40, 50, 60, 70 ]
Custom Recursive Approach to Flattening Array
This method involves creating a function that recursively processes each element of the array. If an element is itself an array, the function will call itself recursively to handle that nested array.
- Define a function that takes an array as input.
- Initialize an empty result array to collect flattened elements.
- Iterate through each element of the input array:
- If the element is an array, recursively call the flatten function and append the result to the result array.
- If the element is not an array, directly append it to the result array.
- Return the result array.
JavaScript
function flattenArray(arr) {
// Initialize an empty array to hold
// the flattened result
let result = [];
// Helper function to recursively flatten elements
function flatten(element) {
if (Array.isArray(element)) {
// If the element is an array, iterate
// through its elements
for (let i = 0; i < element.length; i++) {
flatten(element[i]); // Recursively call flatten
}
} else {
// If the element is not an array,
// add it to the result array
result.push(element);
}
}
// Start the flattening process
flatten(arr);
return result;
}
// Given nested array
let array = [10, [20, 30], [40, [50, 60]], 70];
const flatArray = flattenArray(array);
// Display the flattened array
console.log("Updated Array:", flatArray);
OutputUpdated Array: [
10, 20, 30, 40,
50, 60, 70
]
Similar Reads
How to deep flatten an array in JavaScript? In this article, we will learn how to deep flatten an array in JavaScript. The flattening of an array is a process of merging a group of nested arrays present inside a given array. Deep flattening means that the array would be completely flattened. Example: Input: [1,2,3,4,5,[6,[7,8,9]]] Output: [1,
2 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ? Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional struct
3 min read
How to Merge Two Arrays and Remove Duplicate Items in JavaScript? Given two arrays, the task is to merge both arrays and remove duplicate items from merged array in JavaScript. The basic method to merge two arrays without duplicate items is using spread operator and the set constructor.1. Using Spread Operator and Set() ConstructorThe Spread Operator is used to me
3 min read
How to clone an array in JavaScript ? In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t
6 min read
How to flatten array with the JavaScript/jQuery? Flattening an array in JavaScript or jQuery involves transforming a nested array into a single-level array. This process is essential for simplifying complex data structures and making it easier to manipulate and access array elements. Below are the approaches to flatten an array with JavaScript/Jqu
3 min read
How to Flatten a Given Array up to Specified Depth in JavaScript? Flatten an array in JavaScript is a common task when dealing with nested arrays. The concept of "flatten" means to convert a multi-dimensional array into a single-dimensional array. When you need to control the depth of flattening, JavaScript provides methods to handle this efficiently. This process
2 min read
How to Convert an Array into a Complex Array JavaScript ? Complex arrays can represent multiple dimensions or data with a structure. This article discusses two approaches to converting an array into a more complex array.Table of ContentUsing Multidimensional ArraysUsing Array.from()Using the reduce() MethodUsing the map() Method with slice() MethodUsing Mu
3 min read
How to Filter an Array from all Elements of another Array In JavaScript? Filtering one array from all elements of another array is a common task in JavaScript. This involves removing elements from one array that are present in another array. In this article we will explore different approaches to filter an array from all elements of another array in JavaScript.These are
4 min read
Build Tree Array from Flat Array in JavaScript To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of commen
7 min read
How to Flatten Array of Arrays in TypeScript ? Array flattening is the process of converting a nested array (an array of arrays) into a single-dimensional array where all the elements are at the same level. In other words, it involves transforming an array that contains other arrays as elements into an array that only contains non-array elements
4 min read