Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

flatten array using recursion functions in JavaScript?

Write a program to flatten array using recursion functions in JavaScript?

Flatten array using recurssion method, first we have to uderstand the what is flatten array? Flatten is one approcch or technique with help of flatten we are reducing the multidimensional array to one dimensional array is know as flatten.

 
   //flatten below given array 
  let arr = [1,44, [2, [3,9], 67], 9];
  
  //using recurssion
  function recur(a) {
    let newArr = [];
    for (let i =0 ; i < a.length; i++) {
        const element = a[i];
        if (Array.isArray(element)) {
            newArr.push(...recur(element))
        } else  {
            newArr.push(element)
        }
    }
    
    return newArr;
  }

	console.log(recur(arr))
	output:

	[1,44,2,3,9, 67, 9]

//we can also write the same code using foreach:
function flattenArray(items) {
    const flat = [];
    items.forEach(item => {
      if (Array.isArray(item)) {
        flat.push(...flatten(item));
      } else {
        flat.push(item);
      }
    });
  
    return flat;
  }
   
   console.log(flattenArray(arr))
	output:

	[1,44,2,3,9, 67, 9]
    

To solve this problem the we are using the Recurssion approach and this one of the best solution to fixed this kind of solution. wanted to more about the recurssion. I will writing the sepearte more about it. please let me know if we wanted to more about the recurssion comment me below.

Post a Comment

0 Comments