The problem is to create a function that flattens the given array up to the depth passed as an argument. Depth is basically how deep the array can be in the array. So the task is to create a function that looks like below:
function flatarray(arr, depth)
If the passed array is:
[1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, [13]]], 9];
for depth = 1, it should return [1, 2, 3, 4, 5, 6, 7, 8, 10, 11 , 12, 13, 9]. Here, as the depth is 1, so it will be fully flattened.
for depth = 2, it should return [1, 2, 3, [4, 5, 6, 7, 8], [10, 11, 12, 13], 9]. Here, as the depth is 2, then array inside array should be flattened.
for depth = 3, it should return [1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, 13], 9]. And so on.
const arr = [1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, 13]], 9];
function flatten(arr, depth) {
if (depth === 1) {
return flattenArr(arr);
}
let res = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
res.push(flatten(arr[i], depth - 1));
} else {
res.push(arr[i]);
}
}
return res;
}
function flattenArr(arr) {
let res = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
res = res.concat(flattenArr(arr[i]))
} else {
res.push(arr[i]);
}
}
return res;
}
console.log(flatten(arr, 3));
I was able to do it. But, not sure if this is the best way to do it.
Posting this answer in case someone needs it in the future.
Small edit I made in sk01's answer (added Default parameters and use let instead of var)
P.S.: I tried to edit sk01's answer but it's showing me " Suggested edit queue is full" so I'm posting it as an answer
const arr = [1, 2, 3, [4, 5, [6, 7], 8], [10, 11, [12, 13]], 9];
function flatten(arr, depth = 1) {
if (depth === 1) {
return flattenArr(arr);
}
let res = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
res.push(flatten(arr[i], depth - 1));
} else {
res.push(arr[i]);
}
}
return res;
}
function flattenArr(arr) {
let res = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
res = res.concat(flattenArr(arr[i]))
} else {
res.push(arr[i]);
}
}
return res;
}
console.log(flatten(arr, 3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With