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));

3 comments:

  1. I love how you've taught kids coding and robotics. It's so refreshing to find someone who is teaching kids about coding in an approachable way. I also appreciate that you shared the code for flattening an array. It was interesting to see the different ways you could code the same thing! Learn ASP.NET

    ReplyDelete

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 ...