how to flatten array with reduce in javascript

How to Flatten Array with Reduce in JavaScript

If you have a multi-dimensional array in JavaScript and you want to transform it into a one-dimensional array, you can use the reduce() method. The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value.

Here is an example of how to flatten an array using the reduce() method:


const multiDimArray = [[1, 2, 3], [4, 5], [6]];
const flattenedArray = multiDimArray.reduce((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

In this example, we start with a multi-dimensional array that contains three arrays with different lengths. We apply the reduce() method on this multi-dimensional array and pass in a function that concatenates each array element with the accumulator. The accumulator starts with an empty array [].

The first iteration takes the first array [1, 2, 3] and concatenates it with the accumulator [], resulting in [1, 2, 3]. The second iteration takes the second array [4, 5] and concatenates it with the accumulator [1, 2, 3], resulting in [1, 2, 3, 4, 5]. Finally, the third iteration takes the last array [6] and concatenates it with the accumulator [1, 2, 3, 4, 5], resulting in the final flattened array [1, 2, 3, 4, 5, 6].

There are other ways to flatten an array in JavaScript, such as using the flat() method or the spread operator (...). Here is an example of using the flat() method:


const multiDimArray = [[1, 2, 3], [4, 5], [6]];
const flattenedArray = multiDimArray.flat();
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

The flat() method flattens an array up to the specified depth. By default, it flattens the array by one level. In this example, we pass no arguments to the flat() method, so it flattens the array by one level, resulting in the same flattened array as before.

Another way to flatten an array is to use the spread operator (...) on a new array:


const multiDimArray = [[1, 2, 3], [4, 5], [6]];
const flattenedArray = [].concat(...multiDimArray);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6]

In this example, we create a new empty array [] and use the concat() method with the spread operator (...) on the multi-dimensional array. The spread operator expands the multi-dimensional array into individual elements and passes them as arguments to the concat() method. The concat() method concatenates all the elements into a new array, resulting in the same flattened array as before.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe