How to flatten array with the JavaScript/jQuery?
Last Updated :
19 Jun, 2024
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/Jquery:
Using Array.prototype.flat()
The flat()
method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. Using Infinity
as the depth ensures all nested arrays are fully flattened.
Example: To demonstrate flattening array with array.prototype.flat() method in JavaScript.
JavaScript
const nestedArray = [1, [2, [3, [4]]]];
const flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray);
Using Recursion
A recursive function calls itself to flatten nested arrays. It checks if an element is an array; if so, it concatenates the flattened result of that element, otherwise, it adds the element to the result.
Example: To demonstrate flattening array with recursion method in JavaScript.
JavaScript
function flattenArray(arr) {
let result = [];
arr.forEach(element => {
if (Array.isArray(element)) {
result = result.concat(flattenArray(element));
} else {
result.push(element);
}
});
return result;
}
const nestedArray = [1, [2, [3, [4]]]];
let flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
Using reduce()
Method
The reduce()
method iterates over the array, applying a function that concatenates elements if they are arrays or adds them directly if they are not.
Example: To demonstrate flattening array with reduce() method in JavaScript.
JavaScript
function flattenArray(arr) {
return arr.reduce((acc, val) => Array
.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}
const nestedArray = [1, [2, [3, [4]]]];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);
Using JQuery $.map() method
In jQuery can be used to perform the operation. This method takes the array and a method as input. The second argument which is a method takes elements of original array one by one and return its elements.
Example: To demonstrate flattening array with $map() method in JQuery.
html
<!DOCTYPE HTML>
<html>
<head>
<title>
How to flatten array with
the JavaScript?
</title>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body>
<p id="GFG_UP"></p>
<button onClick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN"></p>
<script>
let up = document.getElementById('GFG_UP');
let down = document.getElementById('GFG_DOWN');
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6, 7];
let arr = [arr1, arr2, 8, 9];
up.innerHTML = "Click on button to get the"
+ " common elements from these array"
+ "<br>Array - [[" + arr[0] + "], ["
+ arr[1] + "], " + arr[2] + ", "
+ arr[3] + "]";
function GFG_Fun() {
down.innerHTML = $.map(arr, function (n) {
return n;
});
}
</script>
</body>
</html>
Output:
JQuery $map() method
Similar Reads
How to Merge/Flatten an array of arrays in JavaScript ? 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 arr
3 min read
Implode an array with jQuery/JavaScript Given an array of elements and the task is to implode (join the elements of an array) the array elements. Method 1: Using join() method: The join() method can be used to join an array with a separator and return it as a string. The join() method takes in the optional parameter of a separator. The se
2 min read
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
JavaScript Array flat() Method The Javascript arr.flat() method was introduced in ES2019. The flat() method in JavaScript creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. If no depth is provided, it defaults to 1.Syntax:arr.flat([depth])Parameters:This method accepts a si
4 min read
How to Create Zip Array in JavaScript ? Working with arrays in JavaScript often requires merging or combining multiple arrays into a single structure. One common operation in array manipulation is known as "zipping," where corresponding elements from multiple arrays are paired together to create a new array. Example:Input: let a = [1, 2,
3 min read