//code1
let sample = [[1, 2, 3], [1, 2, [4, 5]], [2, 3, 78, [10, 11, 22]], 1, 3345];
function flattenArray(arr, depth = 1) {
let flattenedArray = [];
for (let j = 0; j < arr.length; j++) {
if (Array.isArray(arr[j]) && depth > 0) {
flattenedArray.push(...flattenArray(arr[j], depth - 1));
} else {
flattenedArray.push(arr[j]);
}
}
return flattenedArray;
};
console.log(flattenArray(sample, 2));
//code2
let sample = [[1, 2, 3], [1, 2, [4, 5]], [2, 3, 78, [10, 11, 22]], 1, 3345];
Array.prototype.flattenArray = function (depth = 1) {
let flattenedArray = [];
for (let element of this) {
if (Array.isArray(element) && depth > 0) {
flattenedArray.push(...element.flattenArray(depth - 1));
} else {
flattenedArray.push(element);
}
}
return flattenedArray;
};
console.log(sample.flattenArray(2));