There are several ways to flatten an array in JavaScript. Let’s explore some of the ways to flatten an array.
Using the flat() method
The flat() method creates a new array with all array elements added consecutively to the desired depth. The depth parameter is optional. 1 is considered the default depth.
const arr = [1, [2, [3, [4]], 5]];
// Default flatten (depth 1)
console.log(arr.flat()); // [1, 2, [3, [4]], 5]
// Flatten to infinite depth
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5]
// Flatten to depth 2
console.log(arr.flat(2)); // [1, 2, 3, [4], 5]
Using the reduce method with recursion
const arr = [1, [2, [3, [4]], 5]];
const flatten = (array) =>
array.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []);
console.log(flatten(arr)); // [1, 2, 3, 4, 5]
Using concat() and apply()
This method uses concat()
combined with apply()
to flatten an array by one level.
const arr = [1, [2, [3, [4]], 5]];
const flattened = [].concat.apply([], arr);
console.log(flattened); // [1, 2, [3, [4]], 5]
Using spread operator
The Spread operator can also flatten the array to one level.
const arr = [1, [2, [3, [4]], 5]];
let flatArray = [].concat(...arr);
console.log(flatArray); // [1, 2, [3, [4]], 5]
Similar Reads
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays