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
20 stars 3 forks source link

18 - flatten - javascript #73

Open jsartisan opened 3 weeks ago

jsartisan commented 3 weeks ago

index.js

export function flatten(arr, depth = 1) {
  const result = [];

  for (let i = 0; i < arr.length; i++) {
    const current = arr[i];

    if (Array.isArray(current) && depth > 0) {
      result.push(...flatten(current, depth - 1));
    } else {
      result.push(current);
    }
  }

  return result;
}
jsartisan commented 3 weeks ago

Sharing another solution that uses classic for loop instead of reduce.