Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten array with given depth

The problem is to create a function that flattens the given array up to the depth passed as an argument. Depth is basically how deep the array can be in the array. So the task is to create a function that looks like below:

function flatarray(arr, depth)

If the passed array is:

[1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, [13]]], 9];

for depth = 1, it should return [1, 2, 3, 4, 5, 6, 7, 8, 10, 11 , 12, 13, 9]. Here, as the depth is 1, so it will be fully flattened.

for depth = 2, it should return [1, 2, 3, [4, 5, 6, 7, 8], [10, 11, 12, 13], 9]. Here, as the depth is 2, then array inside array should be flattened.

for depth = 3, it should return [1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, 13], 9]. And so on.

like image 980
sk01 Avatar asked Mar 22 '26 09:03

sk01


2 Answers

const arr = [1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, 13]], 9];

function flatten(arr, depth) {
  if (depth === 1) {
    return flattenArr(arr);
  }

  let res = [];

  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res.push(flatten(arr[i], depth - 1));
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

function flattenArr(arr) {
  let res = [];
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(flattenArr(arr[i]))
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

console.log(flatten(arr, 3));

I was able to do it. But, not sure if this is the best way to do it.

Posting this answer in case someone needs it in the future.

like image 105
sk01 Avatar answered Mar 23 '26 23:03

sk01


Small edit I made in sk01's answer (added Default parameters and use let instead of var)

P.S.: I tried to edit sk01's answer but it's showing me " Suggested edit queue is full" so I'm posting it as an answer

const arr = [1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, 13]], 9];

function flatten(arr, depth = 1) {
  if (depth === 1) {
    return flattenArr(arr);
  }

  let res = [];

  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res.push(flatten(arr[i], depth - 1));
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

function flattenArr(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      res = res.concat(flattenArr(arr[i]))
    } else {
      res.push(arr[i]);
    }
  }
  return res;
}

console.log(flatten(arr, 3));
like image 31
Sanket Shah Avatar answered Mar 23 '26 22:03

Sanket Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!