0

I am new to recursion. I can flatten an array and return as a normal array, but if I want to flatten the array and store it inside an object and return the value, for some reason I am losing the value of the previous result, it would be great if you could help me out. PS: I am able to do this by sending the result as an argument every iteration, but I want to do it this way so..

const flatten = (nums) => {
  result = {
    number: [],
  };
  console.log(result);
  for (let num of nums) {
    if (Array.isArray(num)) {
      result = {
        ...result,
        ...flatten(num),
      };
    } else if (typeof num === "number") {
      result = { ...result, number: [...result.number, num] };
    }
  }
  return result;
};

console.log(flatten([[1, 2], [3, [6, [1, 2, 3]], [4, [5]]], [1]]));

and I even tried this below method, I know i am making some mistake, it's just i am unable to find where exactly

const flatten = (nums) => {
  return nums.reduce(
    (acc, ele) => {
      if (Array.isArray(ele)) {
        acc = { ...acc, num: [...flatten(ele)] };
      } else {
        acc = { ...acc, num: [...acc.num, ele] };
      }
      return acc;
    },
    { num: [] }
  );
};

expected output:-

result={
  number:[1,2,3,6,1,2,3,4,5,1]
} 

or

{
  number:[1,2,3,6,1,2,3,4,5,1]
} 
Akshay98
  • 51
  • 1
  • 8
  • 3
    JS has this as a builtin, `array.flat(Infinity)`. What result are you expecting? If you want this as a property on an object, `{number: array.flat(Infinity)}`. Your current code declares a global, `result` -- if you `"use strict"` you'll get an error for this. – ggorlen Aug 13 '21 at 05:07
  • I was trying to do manually, without any inbuilt functions – Akshay98 Aug 13 '21 at 05:27
  • 1
    Then write a [normal flatten](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) by hand and add the object in the caller. It's poor design to hardcode the object in the function because it loses general usefulness, in addition to complicating the code for no reason. See [SRP](https://en.wikipedia.org/wiki/Single-responsibility_principle) – ggorlen Aug 13 '21 at 05:28

5 Answers5

2

You can also do it with an array.reduce() method with recursion.

const items = [1, 2, 3, [5, 5], [[8, 9]], [99], 125];
    
    function flatArray(items) {
      return items.reduce((arrayData, element) => {
        if (Array.isArray(element)) {
          arrayData = [...arrayData, ...flatArray(element)];
        } else {
          arrayData = [...arrayData, element];
        }
        return arrayData;
      }, []);
    };
    
    console.log(flatArray(items));
    // [1, 2, 3, 5, 5, 8, 9, 99, 125]

    const result = {
       number: flatArray(items),
    };
Asif vora
  • 3,163
  • 3
  • 15
  • 31
  • hey, I am constantly trying to make it this way where you give the initial value of .reduce fun as { num: [] } instead of a plain array and keep storing the value inside num array, I tried but i am losing previous value – Akshay98 Aug 13 '21 at 05:25
  • Do simple const result = { number: flatArray(items), }; – Asif vora Aug 13 '21 at 05:49
2

we can achieve this way too please check flat method in developer mozilla site flat

const arr = [1, 2, [3, 4, [5, 6]]];


function flatDeep(arr, d = 1) {
   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
                : arr.slice();
};

flatDeep(arr, Infinity);
Hardik Kothari
  • 1,686
  • 1
  • 15
  • 29
2

Try this

var a = [[1, 2], [3, [6, [1, 2, 3]], [4, [5]]], [1]];

console.log(a.flat(3))
S N Sharma
  • 1,436
  • 2
  • 7
  • 20
2

const array = [[1, 2], [3, [6, [1, 2, 3]], [4, [5]]], [1]];

const output = {number: array.flat(3)};

console.log(output);
Mamunur Rashid
  • 1,095
  • 17
  • 28
1

Your parameter is supposed to be a number array but when you recursively call the method, you are putting a giving it a result object. To use recursion you need to have a consistent method signature.

If you want to know the previous input you need to pass an object that contains the previous array.

You might want to try learning algorithms in a statically typed language like java. javascript is very unforgiving for simple errors like that.

Alex
  • 710
  • 6
  • 8