jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
21 stars 4 forks source link

18 - flatten #30

Open nitish8899 opened 4 months ago

nitish8899 commented 4 months ago

index.js

export const flatten = function(arr, depth = 1, result = []) {
  for (let i = 0, length = arr.length; i < length; i++) {
    const value = arr[i];
    if (Array.isArray(value) && depth > 0) {
      flatten(value, depth - 1, result);
    } else {
      result.push(value);
    }
  }
  return result;
};