AlgoDaily Solution
1function flat(array, depthLevel = 1) {
2 let result = [];
3 array.forEach((item) => {
4 // if the item of the main array is an array itself, call the method recursively
5 // to check the elements inside
6 if (Array.isArray(item) && depthLevel > 0) {
7 result.push(...flat(item, depthLevel - 1));
8 } else result.push(item); // else, push the object into the result
9 });
10 return result;
11}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
12
function flat(array, depthLevel = 1) {
let result = [];
array.forEach((item) => {
// if the item of the main array is an array itself, call the method recursively
// to check the elements inside
if (Array.isArray(item) && depthLevel > 0) {
result.push(flat(item, depthLevel - 1));
} else result.push(item); // else, push the object into the result
});
return result;
}
OUTPUT
Results will appear here.