Code to flatten an array to a given depth in JavaScript


Here is the code to flatten an array to a given depth in JavaScript. There are many ways to code it but using recursion is perhaps the smartest way of them all.

//code1

let sample = [[1, 2, 3], [1, 2, [4, 5]], [2, 3, 78, [10, 11, 22]], 1, 3345];

function flattenArray(arr, depth = 1) {
  let flattenedArray = [];
  for (let j = 0; j < arr.length; j++) {
    if (Array.isArray(arr[j]) && depth > 0) {
      flattenedArray.push(...flattenArray(arr[j], depth - 1));
    } else {
      flattenedArray.push(arr[j]);
    }
  }
  return flattenedArray;
};
console.log(flattenArray(sample, 2));

//code2

let sample = [[1, 2, 3], [1, 2, [4, 5]], [2, 3, 78, [10, 11, 22]], 1, 3345];

Array.prototype.flattenArray = function (depth = 1) {
  let flattenedArray = [];
  for (let element of this) {
    if (Array.isArray(element) && depth > 0) {
      flattenedArray.push(...element.flattenArray(depth - 1));
    } else {
      flattenedArray.push(element);
    }
  }
  return flattenedArray;
};
console.log(sample.flattenArray(2));

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...