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 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