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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Introduction to JavaScript JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
7 min read
JSON Web Token (JWT) A JSON Web Token (JWT) is a standard used to securely transmit information between a client (like a frontend application) and a server (the backend). It is commonly used to verify users' identities, authenticate them, and ensure safe communication between the two. JWTs are mainly used in web apps an
7 min read
Frontend Developer Interview Questions and Answers Frontend development is an important part of web applications, and it is used to build dynamic and user-friendly web applications with an interactive user interface (UI). Many companies are hiring skilled Frontend developers with expertise in HTML, CSS, JavaScript, and modern frameworks and librarie
15+ min read
JavaScript Coding Questions and Answers JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav
15+ min read
Top 95+ Javascript Projects For 2025 JavaScript is a lightweight, cross-platform programming language that powers dynamic and interactive web content. From real-time updates to interactive maps and animations, JavaScript brings web pages to life.Here, we provided 95+ JavaScript projects with source code and ideas to provide hands-on ex
4 min read
Functions in JavaScript Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
5 min read
JavaScript Exercises, Practice Questions and Solutions JavaScript Exercise covers interactive quizzes, tracks progress, and enhances coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your JavaScript proficiency at your own pace. Start coding now! A step-by-step JavaScript practice guide for beginner to adva
3 min read
HTML DOM (Document Object Model) The HTML DOM (Document Object Model) is a programming interface that represents the structure of a web page in a way that programming languages like JavaScript can understand and manipulate. Think of it as a tree of objects where each part of your HTML document (elements, attributes, text) is repres
6 min read