1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/js/flatten-deeply-nested-array.js
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

34 lines
873 B
JavaScript

/**
* @param {any[]} arr
* @param {number} depth
* @return {any[]}
*/
var flat = function (arr, n) {
let stack = [[arr, 0, 0]];
let flattened = [];
while (stack.length) {
let [arr, depth, i] = stack.pop();
if (i >= arr.length) {
// finished with the nested array
continue;
}
// if it's a nested array and not deep enough
if (depth < n && arr[i] instanceof Array) {
// gotta continue with the next element of the array
stack.push([arr, depth, i + 1]);
// gotta start with the first element of the nested
stack.push([arr[i], depth + 1, 0]);
// yielding is done only on the elements themselves
continue;
}
flattened.push(arr[i]);
stack.push([arr, depth, i + 1]);
}
return flattened;
};