Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 15, 2021 08:13 pm GMT

Deep Flatten an Array

Hello all,

In this series we will see a lot of question that are asked in javascript interviews so get ready for it

In this article we will see How to flatten an deeply nested array for example

[1,[2,3,[4,5]]] and convert in into [1,2,3,4,5]

We will learn to flatten an array in 2 ways

  1. Using built in function (flat())

  2. Using recursion

1. Using Flat() method in Javascript

The flat() method is an inbuilt array method that flattens a given array into a newly created one-dimensional array. It concatenates all the elements of the given multidimensional array, and flats upto the specified depth.

var newArr = arr.flat(depth)

By default, the depth limit is 1. It can be 1 to Infinity.

const arr = [1,[2,3,[4,5]]];  // Setting the depth value to  // Infinity to deep flatten the array  const flattened = arr.flat(Infinity);  console.log(flattened)  // Output [1,2,3,4,5]

2. Recursively flat an array (Pollyfill)

Now we will see how do it without using any builtin function or basically writing the pollyfill for flat function

//Flatten an array using recursionconst arr = [1,[2,3,[4,5]]]const flatten = (input)=>{    let result = []    if(!Array.isArray(input)) {        return input;    }    for(let data of input) {        result = result.concat(flatten(data))    }    return result}console.log(flatten(test))// Output [1,2,3,4,5]

Let me explain the code

  1. Iterate through each and every value of an array and check whether it is value or an array using Array.isArray()method.
  2. If it is a value return it and concat it.
  3. If it is an array then follow again from step 1.

Using ES6 features (using reduce())

function flatten(arr) {    return arr.reduce((acc, cur) => acc.concat(Array.isArray(cur) ? flatten(cur) : cur), []);};const arr = [1,[2,3,[4,5]]];const flattened = flatten(arr);console.log(flattened);// Output [1,2,3,4,5]

For better understanding of the code Please refer to the gif below.
You can also check this Github repo for the code
Recursion

Voila
Let me know your thoughts about it and if you like it share it with others.

Image description


Original Link: https://dev.to/mukul_singhal/deep-flatten-an-array-5elf

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To