Here are 5 ways to flatten an array in JavaScript.
- Using Array flat() method
- Using Array reduce() method
- Using Array concat() method
- Using a spread operator
- Using a recursive function
Method 1: Using the Array flat() method
The Array.prototype.flat() method creates a new array with all sub-array elements concatenated recursively up to the specified depth and returns a new array with the sub-array elements concatenated.
Syntax
let newArray = arr.flat([depth]);
Visual Representation
Example
const arr = [['krunal', 'ankit'], [21, 74], ['appdividend', ['PHP', 'JS']]];
console.log(arr.flat(2));
Output
[ 'krunal', 'ankit', 21, 74, 'appdividend', 'PHP', 'JS' ]
Method 2: Using the Array reduce() method
The Array.reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Visual Representation
Example
const arr = [11, [21, 30, 46], 19];
const flatten_arr = arr.reduce((acc, val) => acc.concat(val), []);
console.log(flatten_arr)
Output
[ 11, 21, 30, 46, 19 ]
Method 3: Using the Array concat() method
The array.concat() method is to merge two or more arrays. It concatenates all the elements of an array into a new, flattened array.
Visual Representation
Example
const arr = [11, [21, 30, 46], 19];
const flatten_arr = [].concat.apply([], arr);
console.log(flatten_arr)
Output
[ 11, 21, 30, 46, 19 ]
Method 4: Using the spread operator
The SpreadOperator(…) allows splitting an array into single arguments passed to the function as separate arguments.
Visual Representation
Example
const arr = [11, [21, 30, 46], 19];
const flatten_arr = [].concat(...arr);
console.log(flatten_arr)
Output
[ 11, 21, 30, 46, 19 ]
Method 5: Using a recursive function
The recursive approach will comprehensively flatten an array, regardless of how many levels of nested arrays it contains.
To flatten an n-dimensional array in JavaScript, use the recursive function.
function flatten(arr) {
return arr.reduce(
(acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val),
[]
);
}
const arr = [11, [21, 30, 46], 19];
const flatten_arr = flatten(arr)
console.log(flatten_arr)
Output
[ 11, 21, 30, 46, 19 ]
Conclusion
The best and most reliable way to flatten an array is to use the Array.flat() method.
To flatten an n-level or n-dimensional array, use the recursive function.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.