Flatten an array in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a JavaScript array function that takes in a nested array and returns an array with all the elements present in the array without any nesting.

For example −

//if the input is:
const arr = [[1, 2, 3], [4, 5], [6]];
//then the output should be:
const output = [1, 2, 3, 4, 5, 6];

Therefore, let’s write the code for this function −

Method 1: Using recursion

Here we will loop over the original nested array and recursively push the nested element elements into a new array.

Example

const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
   let res = [];
   for(let i = 0; i < this.length; i++){
      if(Array.isArray(this[i])){
         res.push(...this[i].flatten());
      } else {
         res.push(this[i]);
      };
   };
   return res;
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());

Method 2: Using Arrray.prototype.reduce()

Here we will use the reduce() method to construct a new array like this −

Example

const arr = [[1, 2, 3], [4, 5], [6]];
const flatten = function(){
   return this.reduce((acc, val) => {
      return acc.concat(...val);
   }, []);
};
Array.prototype.flatten = flatten;
console.log(arr.flatten());

Output

The console output for both of the methods will be −

[ 1, 2, 3, 4, 5, 6 ]
raja
Published on 25-Aug-2020 07:08:17
Advertisements