Flattening an Array in JavaScript: A Step-by-Step Guide

Posted by

How to Flatten an Array in JavaScript

Flattening an array in JavaScript means converting a multidimensional array into a one-dimensional array. This can be useful when you need to perform operations on a single array instead of nested arrays. Here’s how you can flatten an array in JavaScript:

Using the flat Method

The flat method is built-in JavaScript method that helps flatten an array. Here’s an example:


let nestedArray = [1, [2, 3], [4, 5]];
let flatArray = nestedArray.flat();

console.log(flatArray);

This will output [1, 2, 3, 4, 5].

Using Recursion

If you prefer a more manual approach, you can flatten an array using recursion. Here’s an example:


function flattenArray(arr) {
  return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}

let nestedArray = [1, [2, 3], [4, 5]];
let flatArray = flattenArray(nestedArray);

console.log(flatArray);

This will also output [1, 2, 3, 4, 5].

Using Concat and Apply

Another approach is to use the concat method with apply to flatten an array. Here’s an example:


let nestedArray = [1, [2, 3], [4, 5]];
let flatArray = [].concat.apply([], nestedArray);

console.log(flatArray);

This will also output [1, 2, 3, 4, 5].

There are multiple ways to flatten an array in JavaScript based on your preference and use case. Choose the method that works best for you and happy coding!