Skip to content

Commit

Permalink
Update flattenDepth
Browse files Browse the repository at this point in the history
  • Loading branch information
vadimfilimonov committed Jul 23, 2023
1 parent 7b12a27 commit b74dfe4
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/flattenDepth.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,21 @@ const flattenDepth = (array, depth = 1) => {
return [];
}

if (depth <= 0) {
return array;
}
const iter = (items, currentDepth) => {
if (currentDepth > depth) {
return items;
}

return items.reduce((acc, item) => {
if (!Array.isArray(item)) {
return [...acc, item];
}

return [...acc, ...iter(item, currentDepth + 1)];
}, []);
};

return flattenDepth(array.flat(), depth - 1);
return iter(array, 1);
};

export default flattenDepth;

0 comments on commit b74dfe4

Please sign in to comment.