//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));
thanks so much...
ReplyDeleteI love how you've taught kids coding and robotics. It's so refreshing to find someone who is teaching kids about coding in an approachable way. I also appreciate that you shared the code for flattening an array. It was interesting to see the different ways you could code the same thing! Learn ASP.NET
ReplyDeletethanks so much...
Delete