Array Flattening

Question  :  Given a nested array on any depth and we need to make it a single array.Eg. :-  Array = [1,2,[3,4,[5,6],7],8] || [1,2,[3,4],5] || [1,2,[3,[4,[5]]]]Output :- [1,2,3,4,5,6,7,8] | [1,2,3,4,5] || [1,2,3,4,5] || [1,2,3,4,5] 
respectively for every input array

Array.prototype.flat() :-

Flatten 1 level deep

const arr1 = [1, 2, [3, 4]]
arr1.flat();

ouptut - [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];arr2.flat();output - [1, 2, 3, 4, [5, 6]]// Flatten 2 levels deepconst arr3 = [2, 2, 5, [5, [5, [6]], 7]];arr3.flat(2);output - [2, 2, 5, 5, 5, [6], 7];** For flattening every level depth we need to pass 'Inifinity' as aurguments to the flat() method **// Flatten all levelsconst arr4 = [2, 2, 5, [5, [5, [6]], 7]];arr4.flat(Infinity);output - [2, 2, 5, 5, 5, 6, 7]; For reference please click here
const flatten = function(arr, result = []) {  for (let i = 0, length = arr.length; i < length; i++) {    const value = arr[i];
if(Array.isArray(value)) {
flatten(value, result);
} else {
result.push(value);
}
}
return result;}Reference taken from here
function deepFlatten(arr) {
return flatten( // return shalowly flattened array
arr.map(x=> // with each x in array
Array.isArray(x) // is x an array?
? deepFlatten(x) // if yes, return deeply flattened x
: x // if no, return just x
)
)
}
Reference taken from here

--

--

--

JavaScript Enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Free Software Tools to help you learn a new skill!

JavaScript: Check Valid Parentheses with a Stack

How to Build a Carousel in React Native

Image of Person Swiping on the Pexel app. The background is blurred and only the phone and hand is in focus

What is ES6 and what JavaScript programmers need to know?

What is “this” (JavaScript “this” simplified)

“this” used in a method; simba is swapped with this in the constructor method

Front-End Web Dev Bootcamp in a Pandemic pt. IV

UI/UX Design: Rapid Prototyping with jQuery in 2020

Build a Linkedin clone using ReactJS, Redux, Styled-components and Firebase

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rakesh Kumar Shaw

Rakesh Kumar Shaw

JavaScript Enthusiast

More from Medium

Journey of DLithe Bootcamp Java Full Stack Developer | Week 5(Apr18-Apr 15)

How do you style your HTML? Is it CSS?

Test, test, test (your symptoms): Makers Day 6