Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Different methods to flatten an array
2.1.
Using built-in methods 
2.2.
Without using built-in methods
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Implement Flatten Method on an Array with and without Inbuilt Methods

Author Malay Gain
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Flattening an array is a process of decreasing the dimensionality of the Array. One can use many inbuilt methods to reduce the dimension of a multidimensional array. For example,

arr=[[1, 2],[3, 4],[5, 6],[7,8]] is a 2-D array. By flattening the array, we can turn it into a 1-D array [1, 2, 3, 4, 5, 6, 7, 8]

 We will also look into how to flatten an array without using any inbuilt functions. 

Different methods to flatten an array

There are many ways to flatten a multidimensional array.

Using built-in methods 

Use of spread (...) operator

In ES6, one can flatten an array by using the spread operator.

function flatten(arr) {
 return [].concat(...arr);
}
var arr = [4, 5, [6, 7]];
console.log(flatten(arr))

Output

[ 4, 5, 6, 7 ]

Using .apply(_) and .concat(_) method

one can use these two methods for flattening an array. We pass two arguments to the apply(_) method - an empty array and the array we want to flatten(arr), then concatenate all the elements(sub-arrays) passed into an empty array. Thus obtaining a 1-dimensional array.

function flatten(arr) {
 return  [].concat.apply([], arr);
}
var arr = [4, 5, [6, 7]];
console.log(flatten(arr))

Output

[ 4, 5, 6, 7 ]

Using .toString(_) and .split(_) method

First, the array will be converted into a string, splitting it by commas. Then every character of the string will be mapped to a number again.

var arr = [4,[5,6,[7,8],9]];
const flatten = arr.toString().split(',').map(Number)
console.log(flatten);

Output

[ 4, 5, 6, 7, 8, 9 ]

Use of flat(_) method

We can flatten an array using flat() method (introduced in ES2019) by specifying the depth of the array. The depth of an array is calculated as the number of levels of the bracket pairs in the array. The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The depth parameter is optional, and when no depth is specified, a depth of 1 is considered by default.

let arr = [4,[5,6,[7,8],9]];
console.log(arr.flat(2));

Output

[ 4, 5, 6, 7, 8, 9 ]

Without using built-in methods

var arr = [4,[5,6,[7,8],9]];
function flatten(arr) 
{
   //here we will store final result
   let ans = [];  
   let main = arr, first;
   //looping
   while(main.length > 0) 
   {   
          first = main[0];
          if(Array.isArray(first)) { 
          Array.prototype.splice.apply(main, [0, 1].concat(first));
       } else {
          ans.push(first);
          main.splice(0, 1);
       }
  }
   return ans;
}
console.log(flatten(arr));

Output

[ 4, 5, 6, 7, 8, 9 ]
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

1. Is there an inbuilt method in javascript to flatten arrays?

Yes, the inbuilt javascript ‘flat()’ (Array.prototype.flat()) method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

2. What is the spread operator usually used for in javascript?

The spread operator (denoted by three dots (...)) is used in javascript to spread the inner contents of an iterable such as an array or an object, representing all internal elements of the container and copying them to the new one where it is used.

Key Takeaways

This article covered implementing the 'flat' method on an array with and without inbuilt methods.

Check out the Coding Ninjas Studio library to better grasp the data structures and algorithms and the guided path for learning javascript from the very basics.

Recommended problems -

 

Meanwhile, you can also practice-wide variety of coding questions frequently asked in interviews on Coding Ninjas Studio. Along with coding questions, one can also find interview experiences of scholars working in renowned product-based companies here. 

Happy learning!

Previous article
Implement Linear Search and Binary Search in an Array
Next article
Implement digital watch/Timer in vanilla JS and show time in HH:MM:SS format
Live masterclass