problems(js): add “2625. Flatten Deeply Nested Array”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
4c3c626f07
commit
0a4eda37ee
1 changed files with 34 additions and 0 deletions
34
problems/js/flatten-deeply-nested-array.js
Normal file
34
problems/js/flatten-deeply-nested-array.js
Normal file
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
* @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;
|
||||
};
|
Loading…
Reference in a new issue