JavaScript: Flatten a nested array
JavaScript Array: Exercise-21 with Solution
Write a JavaScript program to flatten a nested (any depth) array. If you pass shallow, the array will only be flattened to a single level.
Sample Data:
console.log(flatten([1, [2], [3, [[4]]],[5,6]]));
[1, 2, 3, 4, 5, 6]
console.log(flatten([1, [2], [3, [[4]]],[5,6]], true));
[1, 2, 3, [[4]], 5, 6]
Sample Solution:
JavaScript Code:
// Function to flatten a nested array
var flatten = function(a, shallow, r) {
// If the result array (r) is not provided, initialize it as an empty array
if (!r) {
r = [];
}
// If shallow is true, use concat.apply to flatten the array
if (shallow) {
return r.concat.apply(r, a);
}
// Iterate through each element in the array
for (var i = 0; i < a.length; i++) {
// Check if the current element is an array
if (a[i].constructor == Array) {
// Recursively flatten nested arrays
flatten(a[i], shallow, r);
} else {
// If the current element is not an array, push it to the result array
r.push(a[i]);
}
}
// Return the flattened array
return r;
}
// Output the result of the flatten function with a nested array
console.log(flatten([1, [2], [3, [[4]]], [5, 6]]));
// Output the result of the flatten function with a nested array using shallow flattening
console.log(flatten([1, [2], [3, [[4]]], [5, 6]], true));
Output:
[1,2,3,4,5,6] [1,2,3,[[4]],5,6]
Flowchart:
ES6 Version:
// Function to flatten a nested array
const flatten = (a, shallow, r = []) => {
// If shallow is true, use concat and spread syntax to flatten the array
if (shallow) {
return [...r, ...[].concat(...a)];
}
// Iterate through each element in the array
for (let i = 0; i < a.length; i++) {
// Check if the current element is an array
if (Array.isArray(a[i])) {
// Recursively flatten nested arrays
flatten(a[i], shallow, r);
} else {
// If the current element is not an array, push it to the result array
r.push(a[i]);
}
}
// Return the flattened array
return r;
};
// Output the result of the flatten function with a nested array
console.log(flatten([1, [2], [3, [[4]]], [5, 6]]));
// Output the result of the flatten function with a nested array using shallow flattening
console.log(flatten([1, [2], [3, [[4]]], [5, 6]], true));
Live Demo:
See the Pen JavaScript - Flatten a nested array - array-ex- 21 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to find duplicate values in a JavaScript array.
Next: Write a JavaScript program to compute the union of two arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-array-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics