From 4c386b793487fd0a26f4a7b1813f17076aab6acb Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Mon, 27 May 2024 00:51:58 +0300 Subject: [PATCH] refactor: improving readability for flat function --- 3.implement-Array.prototype.flat.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/3.implement-Array.prototype.flat.md b/3.implement-Array.prototype.flat.md index eff5fd3..9f724a0 100644 --- a/3.implement-Array.prototype.flat.md +++ b/3.implement-Array.prototype.flat.md @@ -35,17 +35,17 @@ Are you able to solve it both recursively and iteratively? * @param { Array } arr * @param { number } depth */ -function flat(arr, depth = 1) { +const flat = (array, depth = 1) => { let flatArray = []; - for (const item of arr) { - if (Array.isArray(item) && depth > 0) { - flatArray = flatArray.concat(flat(item, depth - 1)); + array.forEach((element) => { + if (Array.isArray(element) && depth > 0) { + flatArray.push(...flat(element, depth - 1)); } else { - flatArray.push(item); + flatArray.push(element); } - } + }); return flatArray; -} +}; ``` #