Overview
Implement flatten(array, depth) that recursively flattens a nested array up to depth levels. Default depth is 1.
Examples
flatten([1,[2,[3,[4]]]], 1); // [1,2,[3,[4]]] flatten([1,[2,[3,[4]]]], Infinity); // [1,2,3,4]
Solution
Reveal solution
function flatten(array, depth = 1) {
const r = [];
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
r.push(...flatten(item, depth - 1));
} else {
r.push(item);
}
}
return r;
}flatten.js
Flatten
mediumcodingJavaScriptArrays
Overview
Implement flatten(array, depth) that recursively flattens a nested array up to depth levels. Default depth is 1.
Examples
flatten([1,[2,[3,[4]]]], 1); // [1,2,[3,[4]]] flatten([1,[2,[3,[4]]]], Infinity); // [1,2,3,4]
Solution
Reveal solution
function flatten(array, depth = 1) {
const r = [];
for (const item of array) {
if (Array.isArray(item) && depth > 0) {
r.push(...flatten(item, depth - 1));
} else {
r.push(item);
}
}
return r;
}NameTopicDifficulty
103 of 103 problems